@murumets-ee/auth 0.1.4 → 0.2.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.
@@ -1,3 +1,4 @@
1
+ //#region src/admin/routes.d.ts
1
2
  /**
2
3
  * Permission management admin routes for the centralized admin API handler.
3
4
  *
@@ -25,38 +26,38 @@
25
26
  */
26
27
  /** Fire-and-forget audit log function — structurally matches AuditLogFn from @murumets-ee/core */
27
28
  type AuditLogFn = (entry: {
28
- action: string;
29
- entityType?: string;
30
- entityId?: string;
31
- userId?: string;
32
- userName?: string;
33
- changes?: Record<string, unknown>;
34
- metadata?: Record<string, unknown>;
29
+ action: string;
30
+ entityType?: string;
31
+ entityId?: string;
32
+ userId?: string;
33
+ userName?: string;
34
+ changes?: Record<string, unknown>;
35
+ metadata?: Record<string, unknown>;
35
36
  }) => void;
36
37
  interface AdminRoute {
37
- prefix: string;
38
- resource?: string;
39
- actions?: readonly string[];
40
- handlers: Partial<Record<string, (req: Request, ctx: {
41
- segments: string[];
42
- user: {
43
- id: string;
44
- role?: string;
45
- name?: string;
46
- };
47
- audit?: AuditLogFn;
48
- checkPermission: (resource: string, action: string) => boolean;
49
- }) => Promise<Response>>>;
38
+ prefix: string;
39
+ resource?: string;
40
+ actions?: readonly string[];
41
+ handlers: Partial<Record<string, (req: Request, ctx: {
42
+ segments: string[];
43
+ user: {
44
+ id: string;
45
+ role?: string;
46
+ name?: string;
47
+ };
48
+ audit?: AuditLogFn;
49
+ checkPermission: (resource: string, action: string) => boolean;
50
+ }) => Promise<Response>>>;
50
51
  }
51
52
  interface PermissionRoutesConfig {
52
- /** Returns the resource catalog: resource → available actions */
53
- getStatements: () => Record<string, readonly string[]>;
54
- /** Load saved role definitions from settings (null if first run) */
55
- loadRoles: () => Promise<Record<string, Record<string, string[]>> | null>;
56
- /** Save role definitions to settings */
57
- saveRoles: (roles: Record<string, Record<string, string[]>>) => Promise<void>;
58
- /** Called after save to invalidate cached permission checker */
59
- onSave?: () => void;
53
+ /** Returns the resource catalog: resource → available actions */
54
+ getStatements: () => Record<string, readonly string[]>;
55
+ /** Load saved role definitions from settings (null if first run) */
56
+ loadRoles: () => Promise<Record<string, Record<string, string[]>> | null>;
57
+ /** Save role definitions to settings */
58
+ saveRoles: (roles: Record<string, Record<string, string[]>>) => Promise<void>;
59
+ /** Called after save to invalidate cached permission checker */
60
+ onSave?: () => void;
60
61
  }
61
62
  /**
62
63
  * Create admin API routes for permission management.
@@ -68,5 +69,6 @@ interface PermissionRoutesConfig {
68
69
  * - `DELETE /permissions/roles/:name` — Delete a custom role
69
70
  */
70
71
  declare function permissionRoutes(config: PermissionRoutesConfig): AdminRoute;
71
-
72
+ //#endregion
72
73
  export { permissionRoutes };
74
+ //# sourceMappingURL=index.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../../src/admin/routes.ts"],"mappings":";;;;;;;;;;;;;;;;;;AA0CC;;;;;;;;;KARI,UAAA,IAAc,KAAA;EACjB,MAAA;EACA,UAAA;EACA,QAAA;EACA,MAAA;EACA,QAAA;EACA,OAAA,GAAU,MAAA;EACV,QAAA,GAAW,MAAA;AAAA;AAAA,UAGH,UAAA;EACR,MAAA;EACA,QAAA;EACA,OAAA;EACA,QAAA,EAAU,OAAA,CACR,MAAA,UAGI,GAAA,EAAK,OAAA,EACL,GAAA;IACE,QAAA;IACA,IAAA;MAAQ,EAAA;MAAY,IAAA;MAAe,IAAA;IAAA;IACnC,KAAA,GAAQ,UAAA;IACR,eAAA,GAAkB,QAAA,UAAkB,MAAA;EAAA,MAEnC,OAAA,CAAQ,QAAA;AAAA;AAAA,UA8BF,sBAAA;EAAA;EAEf,aAAA,QAAqB,MAAA;;EAErB,SAAA,QAAiB,OAAA,CAAQ,MAAA,SAAe,MAAA;EAAA;EAExC,SAAA,GAAY,KAAA,EAAO,MAAA,SAAe,MAAA,wBAA8B,OAAA;EAF/C;EAIjB,MAAA;AAAA;;;;;;;;;;iBAYc,gBAAA,CAAiB,MAAA,EAAQ,sBAAA,GAAyB,UAAA"}
@@ -0,0 +1,2 @@
1
+ import{r as e}from"../permissions-DREmJByu.mjs";const t=/^[a-z][a-z0-9-]{0,49}$/;function n(e,t=200){return new Response(JSON.stringify(e),{status:t,headers:{"Content-Type":`application/json`}})}function r(e,t){return n({error:e},t)}function i(i){let{getStatements:a,loadRoles:o,saveRoles:s,onSave:c}=i;return{prefix:`permissions`,resource:`permissions`,actions:[`view`,`create`,`update`,`delete`],handlers:{GET:async(t,{segments:r})=>{let i=a(),s=await o()??{};return r.length===1&&r[0]===`roles`?n({roles:Object.keys(s),builtInRoles:[...e]}):n({statements:i,roles:s,builtInRoles:[...e]})},PATCH:async(e,{user:t,audit:i})=>{let{roles:l}=await e.json();if(!l||typeof l!=`object`)return r(`Body must contain "roles" object`,400);if(`admin`in l)return r(`Cannot modify admin role permissions (admin always has full access)`,400);if(t.role&&t.role!==`admin`&&t.role in l)return r(`Cannot modify permissions for your own role`,403);let u=await o()??{};for(let e of Object.keys(l))if(!(e in u))return r(`Role '${e}' does not exist. Create it first via POST /permissions/roles`,400);let d=a();for(let[e,t]of Object.entries(l)){if(typeof e!=`string`||!e)return r(`Role names must be non-empty strings`,400);if(typeof t!=`object`||!t||Array.isArray(t))return r(`Permissions for role '${e}' must be an object`,400);for(let[n,i]of Object.entries(t)){if(!Array.isArray(i)||!i.every(e=>typeof e==`string`))return r(`Actions for '${n}' in role '${e}' must be a string array`,400);let t=d[n];if(!t)return r(`Unknown resource: ${n}`,400);for(let e of i)if(!t.includes(e))return r(`Invalid action '${e}' for resource '${n}'. Valid: ${t.join(`, `)}`,400)}}let f={...u};for(let[e,t]of Object.entries(l))f[e]=t;return await s(f),c?.(),i?.({action:`permissions.update`,entityType:`permissions`,userId:t.id,userName:t.name,changes:{roles:l},metadata:{rolesModified:Object.keys(l)}}),n({ok:!0})},POST:async(i,{segments:a,user:l,audit:u})=>{if(a.length!==1||a[0]!==`roles`)return r(`POST only supported at /permissions/roles`,400);let{name:d}=await i.json();if(!d||typeof d!=`string`)return r(`Body must contain "name" string`,400);if(!t.test(d))return r(`Role name must be lowercase alphanumeric with hyphens, start with a letter, max 50 chars`,400);if(e.includes(d))return r(`Cannot create role with built-in name: ${d}`,400);let f=await o()??{};return d in f?r(`Role already exists: ${d}`,409):(f[d]={},await s(f),c?.(),u?.({action:`permissions.role.create`,entityType:`permissions`,userId:l.id,userName:l.name,changes:{roleName:d}}),n({name:d,permissions:{}},201))},DELETE:async(t,{segments:i,user:a,audit:l})=>{if(i.length!==2||i[0]!==`roles`)return r(`DELETE only supported at /permissions/roles/:name`,400);let u=i[1];if(e.includes(u))return r(`Cannot delete built-in role: ${u}`,400);let d=await o()??{};if(!(u in d))return r(`Role not found: ${u}`,404);let f=d[u];return delete d[u],await s(d),c?.(),l?.({action:`permissions.role.delete`,entityType:`permissions`,userId:a.id,userName:a.name,changes:{roleName:u,permissions:f}}),n({deleted:u})}}}}export{i as permissionRoutes};
2
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../../src/admin/routes.ts"],"sourcesContent":["/**\n * Permission management admin routes for the centralized admin API handler.\n *\n * Provides CRUD for role definitions and permission assignments.\n * Admin-only by default (resource: 'permissions', only admin has access).\n *\n * @example\n * ```typescript\n * import { createAdminApiHandler } from '@murumets-ee/admin-ui/server'\n * import { permissionRoutes } from '@murumets-ee/auth/admin'\n *\n * const handler = createAdminApiHandler({\n * authenticate: async (req) => { ... },\n * entities: [...],\n * routes: [\n * permissionRoutes({\n * getStatements: () => catalog,\n * loadRoles: () => client.get('roles'),\n * saveRoles: (roles) => client.set('roles', roles),\n * onSave: () => { cachedChecker = null },\n * }),\n * ],\n * })\n * ```\n */\n\nimport { BUILT_IN_ROLES } from '../permissions.js'\n\n// ---------------------------------------------------------------------------\n// Local route type — avoids circular build dep: auth → admin-ui → core → auth.\n// Structurally compatible with AdminRoute from @murumets-ee/core.\n// ---------------------------------------------------------------------------\n\n/** Fire-and-forget audit log function — structurally matches AuditLogFn from @murumets-ee/core */\ntype AuditLogFn = (entry: {\n action: string\n entityType?: string\n entityId?: string\n userId?: string\n userName?: string\n changes?: Record<string, unknown>\n metadata?: Record<string, unknown>\n}) => void\n\ninterface AdminRoute {\n prefix: string\n resource?: string\n actions?: readonly string[]\n handlers: Partial<\n Record<\n string,\n (\n req: Request,\n ctx: {\n segments: string[]\n user: { id: string; role?: string; name?: string }\n audit?: AuditLogFn\n checkPermission: (resource: string, action: string) => boolean\n },\n ) => Promise<Response>\n >\n >\n}\n\n// ---------------------------------------------------------------------------\n// Validation\n// ---------------------------------------------------------------------------\n\nconst ROLE_NAME_REGEX = /^[a-z][a-z0-9-]{0,49}$/\n\n// ---------------------------------------------------------------------------\n// Response helpers\n// ---------------------------------------------------------------------------\n\nfunction json(data: unknown, status = 200): Response {\n return new Response(JSON.stringify(data), {\n status,\n headers: { 'Content-Type': 'application/json' },\n })\n}\n\nfunction errorJson(message: string, status: number): Response {\n return json({ error: message }, status)\n}\n\n// ---------------------------------------------------------------------------\n// Route factory\n// ---------------------------------------------------------------------------\n\nexport interface PermissionRoutesConfig {\n /** Returns the resource catalog: resource → available actions */\n getStatements: () => Record<string, readonly string[]>\n /** Load saved role definitions from settings (null if first run) */\n loadRoles: () => Promise<Record<string, Record<string, string[]>> | null>\n /** Save role definitions to settings */\n saveRoles: (roles: Record<string, Record<string, string[]>>) => Promise<void>\n /** Called after save to invalidate cached permission checker */\n onSave?: () => void\n}\n\n/**\n * Create admin API routes for permission management.\n *\n * Routes (all prefixed with `/api/admin/permissions`):\n * - `GET /permissions` — Get statements + roles + builtInRoles\n * - `PATCH /permissions` — Update role permissions\n * - `POST /permissions/roles` — Create a custom role\n * - `DELETE /permissions/roles/:name` — Delete a custom role\n */\nexport function permissionRoutes(config: PermissionRoutesConfig): AdminRoute {\n const { getStatements, loadRoles, saveRoles, onSave } = config\n\n return {\n prefix: 'permissions',\n resource: 'permissions',\n actions: ['view', 'create', 'update', 'delete'],\n handlers: {\n // GET /permissions — full permission data for the editor\n GET: async (_req, { segments }) => {\n const statements = getStatements()\n const roles = (await loadRoles()) ?? {}\n\n // GET /permissions/roles — just role names\n if (segments.length === 1 && segments[0] === 'roles') {\n return json({\n roles: Object.keys(roles),\n builtInRoles: [...BUILT_IN_ROLES],\n })\n }\n\n return json({\n statements,\n roles,\n builtInRoles: [...BUILT_IN_ROLES],\n })\n },\n\n // PATCH /permissions — update role permissions\n PATCH: async (req, { user, audit }) => {\n const body = await req.json()\n const { roles } = body as { roles?: Record<string, Record<string, string[]>> }\n\n if (!roles || typeof roles !== 'object') {\n return errorJson('Body must contain \"roles\" object', 400)\n }\n\n // Validate: admin cannot be modified\n if ('admin' in roles) {\n return errorJson(\n 'Cannot modify admin role permissions (admin always has full access)',\n 400,\n )\n }\n\n // Prevent self-escalation: non-admin users cannot modify their own role\n if (user.role && user.role !== 'admin' && user.role in roles) {\n return errorJson('Cannot modify permissions for your own role', 403)\n }\n\n // Validate: only existing roles can be modified (use POST /roles to create)\n const existing = (await loadRoles()) ?? {}\n for (const roleName of Object.keys(roles)) {\n if (!(roleName in existing)) {\n return errorJson(\n `Role '${roleName}' does not exist. Create it first via POST /permissions/roles`,\n 400,\n )\n }\n }\n\n // Validate: actions must be in statements\n const statements = getStatements()\n for (const [roleName, resources] of Object.entries(roles)) {\n if (typeof roleName !== 'string' || !roleName) {\n return errorJson('Role names must be non-empty strings', 400)\n }\n if (typeof resources !== 'object' || resources === null || Array.isArray(resources)) {\n return errorJson(`Permissions for role '${roleName}' must be an object`, 400)\n }\n for (const [resource, actions] of Object.entries(resources)) {\n if (!Array.isArray(actions) || !actions.every((a) => typeof a === 'string')) {\n return errorJson(\n `Actions for '${resource}' in role '${roleName}' must be a string array`,\n 400,\n )\n }\n const validActions = statements[resource]\n if (!validActions) {\n return errorJson(`Unknown resource: ${resource}`, 400)\n }\n for (const action of actions) {\n if (!validActions.includes(action)) {\n return errorJson(\n `Invalid action '${action}' for resource '${resource}'. Valid: ${validActions.join(', ')}`,\n 400,\n )\n }\n }\n }\n }\n\n // Merge into existing roles (don't drop roles not in the payload)\n const merged = { ...existing }\n for (const [roleName, resources] of Object.entries(roles)) {\n merged[roleName] = resources\n }\n\n await saveRoles(merged)\n onSave?.()\n\n audit?.({\n action: 'permissions.update',\n entityType: 'permissions',\n userId: user.id,\n userName: user.name,\n changes: { roles },\n metadata: { rolesModified: Object.keys(roles) },\n })\n\n return json({ ok: true })\n },\n\n // POST /permissions/roles — create a new custom role\n POST: async (req, { segments, user, audit }) => {\n if (segments.length !== 1 || segments[0] !== 'roles') {\n return errorJson('POST only supported at /permissions/roles', 400)\n }\n\n const body = await req.json()\n const { name } = body as { name?: string }\n\n if (!name || typeof name !== 'string') {\n return errorJson('Body must contain \"name\" string', 400)\n }\n\n if (!ROLE_NAME_REGEX.test(name)) {\n return errorJson(\n 'Role name must be lowercase alphanumeric with hyphens, start with a letter, max 50 chars',\n 400,\n )\n }\n\n if ((BUILT_IN_ROLES as readonly string[]).includes(name)) {\n return errorJson(`Cannot create role with built-in name: ${name}`, 400)\n }\n\n const existing = (await loadRoles()) ?? {}\n\n if (name in existing) {\n return errorJson(`Role already exists: ${name}`, 409)\n }\n\n // New role starts with zero permissions\n existing[name] = {}\n await saveRoles(existing)\n onSave?.()\n\n audit?.({\n action: 'permissions.role.create',\n entityType: 'permissions',\n userId: user.id,\n userName: user.name,\n changes: { roleName: name },\n })\n\n return json({ name, permissions: {} }, 201)\n },\n\n // DELETE /permissions/roles/:name — delete a custom role\n DELETE: async (_req, { segments, user, audit }) => {\n if (segments.length !== 2 || segments[0] !== 'roles') {\n return errorJson('DELETE only supported at /permissions/roles/:name', 400)\n }\n\n const name = segments[1]\n\n if ((BUILT_IN_ROLES as readonly string[]).includes(name)) {\n return errorJson(`Cannot delete built-in role: ${name}`, 400)\n }\n\n const existing = (await loadRoles()) ?? {}\n\n if (!(name in existing)) {\n return errorJson(`Role not found: ${name}`, 404)\n }\n\n const deletedPermissions = existing[name]\n delete existing[name]\n await saveRoles(existing)\n onSave?.()\n\n audit?.({\n action: 'permissions.role.delete',\n entityType: 'permissions',\n userId: user.id,\n userName: user.name,\n changes: { roleName: name, permissions: deletedPermissions },\n })\n\n return json({ deleted: name })\n },\n },\n }\n}\n"],"mappings":"gDAoEA,MAAM,EAAkB,yBAMxB,SAAS,EAAK,EAAe,EAAS,IAAe,CACnD,OAAO,IAAI,SAAS,KAAK,UAAU,EAAK,CAAE,CACxC,SACA,QAAS,CAAE,eAAgB,mBAAoB,CAChD,CAAC,CAGJ,SAAS,EAAU,EAAiB,EAA0B,CAC5D,OAAO,EAAK,CAAE,MAAO,EAAS,CAAE,EAAO,CA2BzC,SAAgB,EAAiB,EAA4C,CAC3E,GAAM,CAAE,gBAAe,YAAW,YAAW,UAAW,EAExD,MAAO,CACL,OAAQ,cACR,SAAU,cACV,QAAS,CAAC,OAAQ,SAAU,SAAU,SAAS,CAC/C,SAAU,CAER,IAAK,MAAO,EAAM,CAAE,cAAe,CACjC,IAAM,EAAa,GAAe,CAC5B,EAAS,MAAM,GAAW,EAAK,EAAE,CAUvC,OAPI,EAAS,SAAW,GAAK,EAAS,KAAO,QACpC,EAAK,CACV,MAAO,OAAO,KAAK,EAAM,CACzB,aAAc,CAAC,GAAG,EAAe,CAClC,CAAC,CAGG,EAAK,CACV,aACA,QACA,aAAc,CAAC,GAAG,EAAe,CAClC,CAAC,EAIJ,MAAO,MAAO,EAAK,CAAE,OAAM,WAAY,CAErC,GAAM,CAAE,SADK,MAAM,EAAI,MAAM,CAG7B,GAAI,CAAC,GAAS,OAAO,GAAU,SAC7B,OAAO,EAAU,mCAAoC,IAAI,CAI3D,GAAI,UAAW,EACb,OAAO,EACL,sEACA,IACD,CAIH,GAAI,EAAK,MAAQ,EAAK,OAAS,SAAW,EAAK,QAAQ,EACrD,OAAO,EAAU,8CAA+C,IAAI,CAItE,IAAM,EAAY,MAAM,GAAW,EAAK,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 +1,100 @@
1
+ import { createAuthClient } from "better-auth/react";
2
+
3
+ //#region src/client.d.ts
4
+ interface AuthClientOptions {
5
+ /** Base URL of the auth API. Defaults to window.location.origin. */
6
+ baseURL?: string;
7
+ /** Enable organization client plugin (must match server config) */
8
+ organizations?: boolean;
9
+ }
10
+ /**
11
+ * Create a typed auth client for use in React components.
12
+ *
13
+ * The explicit `ReturnType<typeof createAuthClient>` annotation is required
14
+ * because better-auth 1.6's client return type references internal modules
15
+ * (`client/path-to-object`, `client/query`) and zod@4 types that tsdown's
16
+ * dts generator cannot name portably across pnpm's symlink paths (TS2742).
17
+ *
18
+ * Widening to the base `createAuthClient` return type loses the plugin-
19
+ * specific client fields (`client.admin.listUsers`, etc.) at type level.
20
+ * Consumers who need typed access to admin endpoints should use
21
+ * `createUsersApi(client)` which bridges to a stable `UsersApi` interface
22
+ * the `@murumets-ee/admin-ui/users` package expects.
23
+ *
24
+ * @example
25
+ * ```typescript
26
+ * // lib/auth-client.ts
27
+ * import { createClient } from '@murumets-ee/auth/client'
28
+ *
29
+ * export const authClient = createClient()
30
+ *
31
+ * // In a component:
32
+ * const { data: session } = authClient.useSession()
33
+ * ```
34
+ */
35
+ declare function createClient(options?: AuthClientOptions): ReturnType<typeof createAuthClient>;
36
+ type AuthClient = any;
37
+ interface UsersListQuery {
38
+ limit: number;
39
+ offset: number;
40
+ sortBy?: string;
41
+ sortDirection?: 'asc' | 'desc';
42
+ searchValue?: string;
43
+ searchField?: 'email' | 'name';
44
+ searchOperator?: 'contains' | 'starts_with' | 'ends_with';
45
+ }
46
+ interface NormalizedUser {
47
+ id: string;
48
+ name: string;
49
+ email: string;
50
+ emailVerified: boolean;
51
+ image: string | null;
52
+ createdAt: string;
53
+ updatedAt: string;
54
+ role: string | null;
55
+ banned: boolean | null;
56
+ banReason: string | null;
57
+ banExpires: string | null;
58
+ }
59
+ /**
60
+ * Create a users API adapter from a better-auth client that includes the
61
+ * `adminClient()` plugin. The returned object is structurally compatible
62
+ * with the `UsersApi` interface from `@murumets-ee/admin-ui/users`.
63
+ *
64
+ * @example
65
+ * ```tsx
66
+ * import { createClient, createUsersApi } from '@murumets-ee/auth/client'
67
+ * import { UsersManagement } from '@murumets-ee/admin-ui/users'
68
+ *
69
+ * const authClient = createClient()
70
+ * const usersApi = createUsersApi(authClient)
71
+ *
72
+ * <UsersManagement api={usersApi} currentUserId={session.user.id} />
73
+ * ```
74
+ */
75
+ declare function createUsersApi(client: AuthClient): {
76
+ list(query: UsersListQuery): Promise<{
77
+ users: NormalizedUser[];
78
+ total: number;
79
+ }>;
80
+ create(data: {
81
+ name: string;
82
+ email: string;
83
+ password: string;
84
+ role: string;
85
+ }): Promise<void>;
86
+ update(userId: string, data: {
87
+ name?: string;
88
+ }): Promise<void>;
89
+ remove(userId: string): Promise<void>;
90
+ setRole(userId: string, role: string): Promise<void>;
91
+ ban(userId: string, options?: {
92
+ reason?: string;
93
+ expiresIn?: number;
94
+ }): Promise<void>;
95
+ unban(userId: string): Promise<void>;
96
+ revokeSessions(userId: string): Promise<void>;
97
+ };
98
+ //#endregion
99
+ export { AuthClientOptions, createClient, createUsersApi };
100
+ //# sourceMappingURL=client.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.d.mts","names":[],"sources":["../src/client.ts"],"mappings":";;;UAUiB,iBAAA;EAgCD;EA9Bd,OAAA;;EAEA,aAAA;AAAA;;;;;;;;;;AAiCD;;;;;AASc;;;;;;;;;;;iBAdC,YAAA,CAAa,OAAA,GAAU,iBAAA,GAAoB,UAAA,QAAkB,gBAAA;AAAA,KAcxE,UAAA;AAAA,UAEK,cAAA;EACR,KAAA;EACA,MAAA;EACA,MAAA;EACA,aAAA;EACA,WAAA;EACA,WAAA;EACA,cAAA;AAAA;AAAA,UAGQ,cAAA;EACR,EAAA;EACA,IAAA;EACA,KAAA;EACA,aAAA;EACA,KAAA;EACA,SAAA;EACA,SAAA;EACA,IAAA;EACA,MAAA;EACA,SAAA;EACA,UAAA;AAAA;;;;;;;;;;;;;;;;;iBAmBc,cAAA,CAAe,MAAA,EAAQ,UAAA;cAYjB,cAAA,GAAiB,OAAA;IAAU,KAAA,EAAO,cAAA;IAAkB,KAAA;EAAA;;IAuBjD,IAAA;IAAc,KAAA;IAAe,QAAA;IAAkB,IAAA;EAAA,IAAc,OAAA;yBAavD,IAAA;IAAU,IAAA;EAAA,IAAe,OAAA;0BAMzB,OAAA;0BAMC,IAAA,WAAc,OAAA;sBASlB,OAAA;IAAc,MAAA;IAAiB,SAAA;EAAA,IAAoB,OAAA;yBAUjD,OAAA;kCAMS,OAAA;AAAA"}
@@ -0,0 +1,2 @@
1
+ import{adminClient as e,organizationClient as t}from"better-auth/client/plugins";import{createAuthClient as n}from"better-auth/react";function r(r){return n({baseURL:r?.baseURL,plugins:[e(),...r?.organizations?[t()]:[]]})}function i(e){function t(e){if(e.error)throw Error(e.error.message??`Unknown error`);return e.data}return{async list(n){let r=t(await e.admin.listUsers({query:{limit:n.limit,offset:n.offset,...n.sortBy?{sortBy:n.sortBy,sortDirection:n.sortDirection}:{},...n.searchValue?{searchValue:n.searchValue,searchField:n.searchField??`email`,searchOperator:n.searchOperator??`contains`}:{}}}));return{users:(r.users??[]).map(a),total:r.total??0}},async create(n){t(await e.admin.createUser({name:n.name,email:n.email,password:n.password,role:n.role}))},async update(n,r){t(await e.admin.updateUser({userId:n,data:r}))},async remove(n){t(await e.admin.removeUser({userId:n}))},async setRole(n,r){t(await e.admin.setRole({userId:n,role:r}))},async ban(n,r){t(await e.admin.banUser({userId:n,...r?.reason?{banReason:r.reason}:{},...r?.expiresIn?{banExpiresIn:r.expiresIn}:{}}))},async unban(n){t(await e.admin.unbanUser({userId:n}))},async revokeSessions(n){t(await e.admin.revokeUserSessions({userId:n}))}}}function a(e){let t=e;return{id:t.id,name:t.name??``,email:t.email,emailVerified:t.emailVerified??!1,image:t.image??null,createdAt:String(t.createdAt??``),updatedAt:String(t.updatedAt??``),role:t.role??null,banned:t.banned??null,banReason:t.banReason??null,banExpires:t.banExpires?String(t.banExpires):null}}export{r as createClient,i as createUsersApi};
2
+ //# sourceMappingURL=client.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.mjs","names":[],"sources":["../src/client.ts"],"sourcesContent":["/**\n * Browser-safe auth client factory.\n *\n * This module has NO server-only imports and is safe to use in React components.\n * Import from '@murumets-ee/auth/client'.\n */\n\nimport { adminClient, organizationClient } from 'better-auth/client/plugins'\nimport { createAuthClient } from 'better-auth/react'\n\nexport interface AuthClientOptions {\n /** Base URL of the auth API. Defaults to window.location.origin. */\n baseURL?: string\n /** Enable organization client plugin (must match server config) */\n organizations?: boolean\n}\n\n/**\n * Create a typed auth client for use in React components.\n *\n * The explicit `ReturnType<typeof createAuthClient>` annotation is required\n * because better-auth 1.6's client return type references internal modules\n * (`client/path-to-object`, `client/query`) and zod@4 types that tsdown's\n * dts generator cannot name portably across pnpm's symlink paths (TS2742).\n *\n * Widening to the base `createAuthClient` return type loses the plugin-\n * specific client fields (`client.admin.listUsers`, etc.) at type level.\n * Consumers who need typed access to admin endpoints should use\n * `createUsersApi(client)` which bridges to a stable `UsersApi` interface\n * the `@murumets-ee/admin-ui/users` package expects.\n *\n * @example\n * ```typescript\n * // lib/auth-client.ts\n * import { createClient } from '@murumets-ee/auth/client'\n *\n * export const authClient = createClient()\n *\n * // In a component:\n * const { data: session } = authClient.useSession()\n * ```\n */\nexport function createClient(options?: AuthClientOptions): ReturnType<typeof createAuthClient> {\n return createAuthClient({\n baseURL: options?.baseURL,\n plugins: [adminClient(), ...(options?.organizations ? [organizationClient()] : [])],\n })\n}\n\n// ---------------------------------------------------------------------------\n// UsersApi adapter — bridges better-auth admin client → @murumets-ee/admin-ui/users\n// ---------------------------------------------------------------------------\n\n// biome-ignore lint/suspicious/noExplicitAny: client.admin.* methods live on a\n// plugin-extended type that our explicit annotation on `createClient` loses.\n// `createUsersApi` casts through `any` and validates the shape at call sites.\ntype AuthClient = any\n\ninterface UsersListQuery {\n limit: number\n offset: number\n sortBy?: string\n sortDirection?: 'asc' | 'desc'\n searchValue?: string\n searchField?: 'email' | 'name'\n searchOperator?: 'contains' | 'starts_with' | 'ends_with'\n}\n\ninterface NormalizedUser {\n id: string\n name: string\n email: string\n emailVerified: boolean\n image: string | null\n createdAt: string\n updatedAt: string\n role: string | null\n banned: boolean | null\n banReason: string | null\n banExpires: string | null\n}\n\n/**\n * Create a users API adapter from a better-auth client that includes the\n * `adminClient()` plugin. The returned object is structurally compatible\n * with the `UsersApi` interface from `@murumets-ee/admin-ui/users`.\n *\n * @example\n * ```tsx\n * import { createClient, createUsersApi } from '@murumets-ee/auth/client'\n * import { UsersManagement } from '@murumets-ee/admin-ui/users'\n *\n * const authClient = createClient()\n * const usersApi = createUsersApi(authClient)\n *\n * <UsersManagement api={usersApi} currentUserId={session.user.id} />\n * ```\n */\nexport function createUsersApi(client: AuthClient) {\n /**\n * Unwrap better-auth's discriminated union response.\n * On error branch, `error` exists with optional `message`.\n * On success branch, `data` exists.\n */\n function unwrap<T>(res: { data?: T; error?: { message?: string } }): T {\n if (res.error) throw new Error(res.error.message ?? 'Unknown error')\n return res.data as T\n }\n\n return {\n async list(query: UsersListQuery): Promise<{ users: NormalizedUser[]; total: number }> {\n const res = await client.admin.listUsers({\n query: {\n limit: query.limit,\n offset: query.offset,\n ...(query.sortBy ? { sortBy: query.sortBy, sortDirection: query.sortDirection } : {}),\n ...(query.searchValue\n ? {\n searchValue: query.searchValue,\n searchField: query.searchField ?? 'email',\n searchOperator: query.searchOperator ?? 'contains',\n }\n : {}),\n },\n })\n // biome-ignore lint/suspicious/noExplicitAny: better-auth's union return type doesn't match a simple generic pattern\n const data = unwrap<{ users: unknown[]; total: number }>(res as any)\n return {\n users: (data.users ?? []).map(mapUser),\n total: data.total ?? 0,\n }\n },\n\n async create(data: { name: string; email: string; password: string; role: string }) {\n const res = await client.admin.createUser({\n name: data.name,\n email: data.email,\n password: data.password,\n // better-auth admin plugin types role as a narrow union; cast is safe\n // because server validates the role against configured access control\n role: data.role as 'admin',\n })\n // biome-ignore lint/suspicious/noExplicitAny: better-auth union return type\n unwrap(res as any)\n },\n\n async update(userId: string, data: { name?: string }) {\n const res = await client.admin.updateUser({ userId, data })\n // biome-ignore lint/suspicious/noExplicitAny: better-auth union return type\n unwrap(res as any)\n },\n\n async remove(userId: string) {\n const res = await client.admin.removeUser({ userId })\n // biome-ignore lint/suspicious/noExplicitAny: better-auth union return type\n unwrap(res as any)\n },\n\n async setRole(userId: string, role: string) {\n const res = await client.admin.setRole({\n userId,\n role: role as 'admin',\n })\n // biome-ignore lint/suspicious/noExplicitAny: better-auth union return type\n unwrap(res as any)\n },\n\n async ban(userId: string, options?: { reason?: string; expiresIn?: number }) {\n const res = await client.admin.banUser({\n userId,\n ...(options?.reason ? { banReason: options.reason } : {}),\n ...(options?.expiresIn ? { banExpiresIn: options.expiresIn } : {}),\n })\n // biome-ignore lint/suspicious/noExplicitAny: better-auth union return type\n unwrap(res as any)\n },\n\n async unban(userId: string) {\n const res = await client.admin.unbanUser({ userId })\n // biome-ignore lint/suspicious/noExplicitAny: better-auth union return type\n unwrap(res as any)\n },\n\n async revokeSessions(userId: string) {\n const res = await client.admin.revokeUserSessions({ userId })\n // biome-ignore lint/suspicious/noExplicitAny: better-auth union return type\n unwrap(res as any)\n },\n }\n}\n\n/** Normalize a better-auth user record to a consistent shape. */\nfunction mapUser(u: unknown): NormalizedUser {\n const r = u as Record<string, unknown>\n return {\n id: r.id as string,\n name: (r.name as string) ?? '',\n email: r.email as string,\n emailVerified: (r.emailVerified as boolean) ?? false,\n image: (r.image as string) ?? null,\n createdAt: String(r.createdAt ?? ''),\n updatedAt: String(r.updatedAt ?? ''),\n role: (r.role as string) ?? null,\n banned: (r.banned as boolean) ?? null,\n banReason: (r.banReason as string) ?? null,\n banExpires: r.banExpires ? String(r.banExpires) : null,\n }\n}\n"],"mappings":"sIA0CA,SAAgB,EAAa,EAAkE,CAC7F,OAAO,EAAiB,CACtB,QAAS,GAAS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Q,OAAQ,CAAG,EAAE,CACxD,GAAI,GAAS,UAAY,CAAE,aAAc,EAAQ,UAAW,CAAG,EAAE,CAClE,CAAC,CAEgB,EAGpB,MAAM,MAAM,EAAgB,CAG1B,EAFY,MAAM,EAAO,MAAM,UAAU,CAAE,SAAQ,CAAC,CAElC,EAGpB,MAAM,eAAe,EAAgB,CAGnC,EAFY,MAAM,EAAO,MAAM,mBAAmB,CAAE,SAAQ,CAAC,CAE3C,EAErB,CAIH,SAAS,EAAQ,EAA4B,CAC3C,IAAM,EAAI,EACV,MAAO,CACL,GAAI,EAAE,GACN,KAAO,EAAE,MAAmB,GAC5B,MAAO,EAAE,MACT,cAAgB,EAAE,eAA6B,GAC/C,MAAQ,EAAE,OAAoB,KAC9B,UAAW,OAAO,EAAE,WAAa,GAAG,CACpC,UAAW,OAAO,EAAE,WAAa,GAAG,CACpC,KAAO,EAAE,MAAmB,KAC5B,OAAS,EAAE,QAAsB,KACjC,UAAY,EAAE,WAAwB,KACtC,WAAY,EAAE,WAAa,OAAO,EAAE,WAAW,CAAG,KACnD"}
@@ -1,21 +1,10 @@
1
- import { RequestContext, PermissionChecker } from '@murumets-ee/core';
2
- import { A as Auth } from './plugin-C-MA3A5U.js';
3
- export { a as AuthConfig, b as auth, g as getAuth } from './plugin-C-MA3A5U.js';
4
- import * as better_auth_plugins from 'better-auth/plugins';
5
- import { Entity } from '@murumets-ee/entity';
6
- import { createAccessControl } from 'better-auth/plugins/access';
7
- export { createAccessControl } from 'better-auth/plugins/access';
8
- import 'better-auth';
9
- import '@murumets-ee/logging';
10
-
11
- /**
12
- * Bridge between better-auth sessions and the toolkit's RequestContext.
13
- *
14
- * This is the critical integration point: it resolves a better-auth session
15
- * from request headers and returns a toolkit RequestContext that the entity
16
- * system's AdminClient, QueryClient, and auditable behavior can read.
17
- */
1
+ import { i as AuthConfig, n as getAuth, r as Auth, t as auth } from "./plugin-BS-ho4BN.mjs";
2
+ import { createAccessControl } from "better-auth/plugins/access";
3
+ import * as _$better_auth_plugins0 from "better-auth/plugins";
4
+ import { PermissionChecker, RequestContext } from "@murumets-ee/core";
5
+ import { Entity } from "@murumets-ee/entity";
18
6
 
7
+ //#region src/context.d.ts
19
8
  /**
20
9
  * Resolve a better-auth session into a toolkit RequestContext.
21
10
  *
@@ -36,10 +25,10 @@ import '@murumets-ee/logging';
36
25
  * ```
37
26
  */
38
27
  declare function resolveAuthContext(auth: Auth, headers: Headers): Promise<RequestContext>;
39
-
28
+ //#endregion
29
+ //#region src/permissions.d.ts
40
30
  declare const ACTIONS: readonly ["view", "create", "update", "delete"];
41
31
  declare const ACTIONS_WITH_PUBLISH: readonly ["view", "create", "update", "delete", "publish"];
42
-
43
32
  /** Built-in role names — cannot be deleted via the roles editor. */
44
33
  declare const BUILT_IN_ROLES: readonly ["admin", "public", "authenticated"];
45
34
  /** Maps HTTP methods to permission action names. */
@@ -72,13 +61,13 @@ declare function buildPermissionChecker(roleDefinitions: Record<string, Record<s
72
61
  * Routes with `resource` and `actions` are added if not already present.
73
62
  */
74
63
  declare function buildResourceCatalog(entities: {
64
+ name: string;
65
+ behaviors?: {
75
66
  name: string;
76
- behaviors?: {
77
- name: string;
78
- }[];
67
+ }[];
79
68
  }[], routes?: {
80
- resource?: string;
81
- actions?: readonly string[];
69
+ resource?: string;
70
+ actions?: readonly string[];
82
71
  }[]): Record<string, string[]>;
83
72
  /**
84
73
  * Build a permission statement object from all registered entities,
@@ -95,20 +84,21 @@ declare function buildStatements(entities: Entity[]): Record<string, readonly st
95
84
  * - **authenticated**: view only (better-auth's `defaultRole`)
96
85
  */
97
86
  declare function buildDefaultRoles(ac: ReturnType<typeof createAccessControl>, entities: Entity[]): {
98
- admin: {
99
- authorize<K_1 extends string>(request: K_1 extends infer T extends K ? { [key in T]?: better_auth_plugins.Subset<string, better_auth_plugins.Statements>[key] | {
100
- actions: better_auth_plugins.Subset<string, better_auth_plugins.Statements>[key];
101
- connector: "OR" | "AND";
102
- } | undefined; } : never, connector?: "OR" | "AND"): better_auth_plugins.AuthorizeResponse;
103
- statements: better_auth_plugins.Subset<string, better_auth_plugins.Statements>;
104
- };
105
- authenticated: {
106
- authorize<K_1 extends string>(request: K_1 extends infer T extends K ? { [key in T]?: better_auth_plugins.Subset<string, better_auth_plugins.Statements>[key] | {
107
- actions: better_auth_plugins.Subset<string, better_auth_plugins.Statements>[key];
108
- connector: "OR" | "AND";
109
- } | undefined; } : never, connector?: "OR" | "AND"): better_auth_plugins.AuthorizeResponse;
110
- statements: better_auth_plugins.Subset<string, better_auth_plugins.Statements>;
111
- };
87
+ admin: {
88
+ authorize<K_1 extends string>(request: K_1 extends infer T extends K ? { [key in T]?: _$better_auth_plugins0.Subset<string, _$better_auth_plugins0.Statements>[key] | {
89
+ actions: _$better_auth_plugins0.Subset<string, _$better_auth_plugins0.Statements>[key];
90
+ connector: "OR" | "AND";
91
+ } | undefined } : never, connector?: "OR" | "AND"): _$better_auth_plugins0.AuthorizeResponse;
92
+ statements: _$better_auth_plugins0.Subset<string, _$better_auth_plugins0.Statements>;
93
+ };
94
+ authenticated: {
95
+ authorize<K_1 extends string>(request: K_1 extends infer T extends K ? { [key in T]?: _$better_auth_plugins0.Subset<string, _$better_auth_plugins0.Statements>[key] | {
96
+ actions: _$better_auth_plugins0.Subset<string, _$better_auth_plugins0.Statements>[key];
97
+ connector: "OR" | "AND";
98
+ } | undefined } : never, connector?: "OR" | "AND"): _$better_auth_plugins0.AuthorizeResponse;
99
+ statements: _$better_auth_plugins0.Subset<string, _$better_auth_plugins0.Statements>;
100
+ };
112
101
  };
113
-
114
- export { ACTIONS, ACTIONS_WITH_PUBLISH, Auth, BUILT_IN_ROLES, METHOD_TO_ACTION, buildDefaultRoles, buildInitialRoleDefinitions, buildPermissionChecker, buildResourceCatalog, buildStatements, resolveAuthContext };
102
+ //#endregion
103
+ export { ACTIONS, ACTIONS_WITH_PUBLISH, type Auth, type AuthConfig, BUILT_IN_ROLES, METHOD_TO_ACTION, auth, buildDefaultRoles, buildInitialRoleDefinitions, buildPermissionChecker, buildResourceCatalog, buildStatements, createAccessControl, getAuth, resolveAuthContext };
104
+ //# sourceMappingURL=index.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/context.ts","../src/permissions.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;iBA8BsB,kBAAA,CAAmB,IAAA,EAAM,IAAA,EAAM,OAAA,EAAS,OAAA,GAAU,OAAA,CAAQ,cAAA;;;cCf1E,OAAA;AAAA,cACA,oBAAA;;cASO,cAAA;;cAGA,gBAAA,EAAkB,MAAA;;;;;;;iBAiBf,2BAAA,CAAA,GAA+B,MAAA,SAAe,MAAA;;AAhCE;;;;;AAED;;iBA6C/C,sBAAA,CACd,eAAA,EAAiB,MAAA,SAAe,MAAA,sBAC/B,iBAAA;;;AArCH;;;;;AAGA;;;;iBAwEgB,oBAAA,CACd,QAAA;EAAY,IAAA;EAAc,SAAA;IAAc,IAAA;EAAA;AAAA,KACxC,MAAA;EAAW,QAAA;EAAmB,OAAA;AAAA,MAC7B,MAAA;;;;;;;;iBA+Ca,eAAA,CAAgB,QAAA,EAAU,MAAA,KAAQ,MAAA;;;;AAlDlD;;;iBAkEgB,iBAAA,CAAkB,EAAA,EAAI,UAAA,QAAkB,mBAAA,GAAsB,QAAA,EAAU,MAAA"}
package/dist/index.mjs ADDED
@@ -0,0 +1,2 @@
1
+ import{a as e,c as t,i as n,l as r,n as i,o as a,r as o,s,t as c,u as l}from"./permissions-DREmJByu.mjs";import{auth as u,getAuth as d}from"./plugin.mjs";import"server-only";async function f(e,t){let n=await e.api.getSession({headers:t});return n?{user:{id:n.user.id,groups:[n.user.role??`viewer`],name:n.user.name??void 0,email:n.user.email??void 0},requestId:crypto.randomUUID()}:{requestId:crypto.randomUUID()}}export{c as ACTIONS,i as ACTIONS_WITH_PUBLISH,o as BUILT_IN_ROLES,n as METHOD_TO_ACTION,u as auth,e as buildDefaultRoles,a as buildInitialRoleDefinitions,s as buildPermissionChecker,t as buildResourceCatalog,r as buildStatements,l as createAccessControl,d as getAuth,f as resolveAuthContext};
2
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/context.ts"],"sourcesContent":["/**\n * Bridge between better-auth sessions and the toolkit's RequestContext.\n *\n * This is the critical integration point: it resolves a better-auth session\n * from request headers and returns a toolkit RequestContext that the entity\n * system's AdminClient, QueryClient, and auditable behavior can read.\n */\n\nimport type { RequestContext } from '@murumets-ee/core'\nimport type { Auth } from './server.js'\n\n/**\n * Resolve a better-auth session into a toolkit RequestContext.\n *\n * Call this from your Next.js middleware or server component to populate\n * the toolkit's AsyncLocalStorage context.\n *\n * @example\n * ```typescript\n * // middleware.ts (user writes this — documented copy-paste)\n * import { getAuth, resolveAuthContext } from '@murumets-ee/auth'\n * import { runWithContext } from '@murumets-ee/core'\n *\n * export async function middleware(request: NextRequest) {\n * const auth = getAuth()\n * const ctx = await resolveAuthContext(auth, request.headers)\n * return runWithContext(ctx, () => NextResponse.next())\n * }\n * ```\n */\nexport async function resolveAuthContext(auth: Auth, headers: Headers): Promise<RequestContext> {\n const session = await auth.api.getSession({ headers })\n\n if (!session) {\n return { requestId: crypto.randomUUID() }\n }\n\n return {\n user: {\n id: session.user.id,\n // The admin plugin stores role on the user object\n groups: [((session.user as Record<string, unknown>).role as string) ?? 'viewer'],\n name: session.user.name ?? undefined,\n email: session.user.email ?? undefined,\n },\n requestId: crypto.randomUUID(),\n }\n}\n"],"mappings":"8KA8BA,eAAsB,EAAmB,EAAY,EAA2C,CAC9F,IAAM,EAAU,MAAM,EAAK,IAAI,WAAW,CAAE,UAAS,CAAC,CAMtD,OAJK,EAIE,CACL,KAAM,CACJ,GAAI,EAAQ,KAAK,GAEjB,OAAQ,CAAG,EAAQ,KAAiC,MAAmB,SAAS,CAChF,KAAM,EAAQ,KAAK,MAAQ,IAAA,GAC3B,MAAO,EAAQ,KAAK,OAAS,IAAA,GAC9B,CACD,UAAW,OAAO,YAAY,CAC/B,CAZQ,CAAE,UAAW,OAAO,YAAY,CAAE"}
@@ -0,0 +1,2 @@
1
+ import{createAccessControl as e}from"better-auth/plugins/access";const t=[`view`,`create`,`update`,`delete`],n=[`view`,`create`,`update`,`delete`,`publish`],r=[`admin`,`public`,`authenticated`],i={GET:`view`,POST:`create`,PATCH:`update`,DELETE:`delete`};function a(){return{public:{},authenticated:{}}}function o(e){let t=new Map;for(let[n,r]of Object.entries(e)){let e=new Map;for(let[t,n]of Object.entries(r))e.set(t,new Set(n));t.set(n,e)}return(e,n,r)=>e===`admin`?!0:t.get(e)?.get(n)?.has(r)??!1}function s(e){return e.behaviors?.some(e=>e.name===`publishable`)??!1}function c(e,t){let n={};for(let t of e)n[t.name]=s(t)?[`view`,`create`,`update`,`delete`,`publish`]:[`view`,`create`,`update`,`delete`];if(t)for(let e of t)e.resource&&e.actions&&!(e.resource in n)&&(n[e.resource]=[...e.actions]);return n}const l={user:[`create`,`list`,`set-role`,`ban`,`impersonate`,`delete`,`set-password`,`get`,`update`],session:[`list`,`revoke`,`delete`]};function u(e){let r={...l};for(let i of e)r[i.name]=s(i)?n:t;return r}function d(e,t){let n={},r={};n.user=[...l.user],n.session=[...l.session],r.user=[],r.session=[];for(let e of t)n[e.name]=s(e)?[`view`,`create`,`update`,`delete`,`publish`]:[`view`,`create`,`update`,`delete`],r[e.name]=[`view`];return{admin:e.newRole(n),authenticated:e.newRole(r)}}export{d as a,c,i,u as l,n,a as o,r,o as s,t,e as u};
2
+ //# sourceMappingURL=permissions-DREmJByu.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"permissions-DREmJByu.mjs","names":[],"sources":["../src/permissions.ts"],"sourcesContent":["/**\n * Permission system — bridges entity access definitions to better-auth's access control,\n * and provides the configurable permission checker for the admin API.\n *\n * Two layers:\n * 1. **better-auth integration**: `buildStatements` / `buildDefaultRoles` — feeds into\n * better-auth's `createAccessControl` for its internal permission system.\n * 2. **Admin API enforcement**: `buildPermissionChecker` / `buildInitialRoleDefinitions` —\n * the toolkit's own firewall-model permission system, persisted in settings.\n */\n\nimport type { PermissionChecker } from '@murumets-ee/core'\nimport type { Entity } from '@murumets-ee/entity'\nimport { createAccessControl } from 'better-auth/plugins/access'\n\nconst ACTIONS = ['view', 'create', 'update', 'delete'] as const\nconst ACTIONS_WITH_PUBLISH = ['view', 'create', 'update', 'delete', 'publish'] as const\n\nexport { ACTIONS, ACTIONS_WITH_PUBLISH }\n\n// ---------------------------------------------------------------------------\n// Built-in roles & constants\n// ---------------------------------------------------------------------------\n\n/** Built-in role names — cannot be deleted via the roles editor. */\nexport const BUILT_IN_ROLES = ['admin', 'public', 'authenticated'] as const\n\n/** Maps HTTP methods to permission action names. */\nexport const METHOD_TO_ACTION: Record<string, string> = {\n GET: 'view',\n POST: 'create',\n PATCH: 'update',\n DELETE: 'delete',\n}\n\n// ---------------------------------------------------------------------------\n// Admin API permission system (firewall model)\n// ---------------------------------------------------------------------------\n\n/**\n * Build initial role definitions for first run (no settings saved yet).\n *\n * All built-in non-admin roles start with ZERO permissions.\n * Admin is never stored — it's hardcoded in the checker.\n */\nexport function buildInitialRoleDefinitions(): Record<string, Record<string, string[]>> {\n return {\n public: {},\n authenticated: {},\n }\n}\n\n/**\n * Build a synchronous permission checker from role definitions.\n *\n * Rules:\n * - `admin` role: ALWAYS returns `true` (hardcoded safety net, ignores settings)\n * - All other roles: exact match from `roleDefinitions` (deny-by-default)\n * - Unknown role / unknown resource / unknown action → `false`\n */\nexport function buildPermissionChecker(\n roleDefinitions: Record<string, Record<string, string[]>>,\n): PermissionChecker {\n // Pre-build lookup maps for O(1) checks\n const perms = new Map<string, Map<string, Set<string>>>()\n\n for (const [role, resources] of Object.entries(roleDefinitions)) {\n const resourceMap = new Map<string, Set<string>>()\n for (const [resource, actions] of Object.entries(resources)) {\n resourceMap.set(resource, new Set(actions))\n }\n perms.set(role, resourceMap)\n }\n\n return (role: string, resource: string, action: string): boolean => {\n if (role === 'admin') return true // Safety net — admin always passes\n return perms.get(role)?.get(resource)?.has(action) ?? false\n }\n}\n\n// ---------------------------------------------------------------------------\n// Resource catalog builder\n// ---------------------------------------------------------------------------\n\n/** Check if an entity has the publishable behavior. */\nfunction isPublishable(entity: { behaviors?: { name: string }[] }): boolean {\n return entity.behaviors?.some((b) => b.name === 'publishable') ?? false\n}\n\n/**\n * Build a complete resource catalog from entities and admin routes.\n *\n * Used by:\n * - `permissionRoutes()` config (`getStatements` callback)\n * - Server-side permission page data loaders\n *\n * Entities automatically get CRUD actions. Publishable entities also get\n * the `publish` action, which gates who can set status to 'published'.\n * Routes with `resource` and `actions` are added if not already present.\n */\nexport function buildResourceCatalog(\n entities: { name: string; behaviors?: { name: string }[] }[],\n routes?: { resource?: string; actions?: readonly string[] }[],\n): Record<string, string[]> {\n const catalog: Record<string, string[]> = {}\n\n for (const entity of entities) {\n catalog[entity.name] = isPublishable(entity)\n ? ['view', 'create', 'update', 'delete', 'publish']\n : ['view', 'create', 'update', 'delete']\n }\n\n if (routes) {\n for (const route of routes) {\n if (route.resource && route.actions && !(route.resource in catalog)) {\n catalog[route.resource] = [...route.actions]\n }\n }\n }\n\n return catalog\n}\n\n// ---------------------------------------------------------------------------\n// better-auth integration (unchanged, used by createAuthServer)\n// ---------------------------------------------------------------------------\n\n/** Admin plugin's built-in resources — must be included for listUsers, ban, etc. */\nconst ADMIN_STATEMENTS = {\n user: [\n 'create',\n 'list',\n 'set-role',\n 'ban',\n 'impersonate',\n 'delete',\n 'set-password',\n 'get',\n 'update',\n ] as const,\n session: ['list', 'revoke', 'delete'] as const,\n}\n\n/**\n * Build a permission statement object from all registered entities,\n * plus the admin plugin's built-in user/session resources.\n *\n * Publishable entities get the additional `publish` action.\n * Result shape: `{ user: [...], session: [...], article: ['view', ...], category: [...] }`\n */\nexport function buildStatements(entities: Entity[]) {\n const statement: Record<string, readonly string[]> = {\n ...ADMIN_STATEMENTS,\n }\n for (const entity of entities) {\n statement[entity.name] = isPublishable(entity) ? ACTIONS_WITH_PUBLISH : ACTIONS\n }\n return statement\n}\n\n/**\n * Build the default toolkit roles for better-auth's access control.\n *\n * - **admin**: full CRUD on all entities + user/session management\n * - **authenticated**: view only (better-auth's `defaultRole`)\n */\nexport function buildDefaultRoles(ac: ReturnType<typeof createAccessControl>, entities: Entity[]) {\n const adminPerms: Record<string, string[]> = {}\n const authenticatedPerms: Record<string, string[]> = {}\n\n // Admin gets full control of user/session management\n adminPerms.user = [...ADMIN_STATEMENTS.user]\n adminPerms.session = [...ADMIN_STATEMENTS.session]\n // Authenticated gets no user/session management\n authenticatedPerms.user = []\n authenticatedPerms.session = []\n\n for (const entity of entities) {\n adminPerms[entity.name] = isPublishable(entity)\n ? ['view', 'create', 'update', 'delete', 'publish']\n : ['view', 'create', 'update', 'delete']\n authenticatedPerms[entity.name] = ['view']\n }\n\n return {\n admin: ac.newRole(adminPerms),\n authenticated: ac.newRole(authenticatedPerms),\n }\n}\n\nexport { createAccessControl }\n"],"mappings":"iEAeA,MAAM,EAAU,CAAC,OAAQ,SAAU,SAAU,SAAS,CAChD,EAAuB,CAAC,OAAQ,SAAU,SAAU,SAAU,UAAU,CASjE,EAAiB,CAAC,QAAS,SAAU,gBAAgB,CAGrD,EAA2C,CACtD,IAAK,OACL,KAAM,SACN,MAAO,SACP,OAAQ,SACT,CAYD,SAAgB,GAAwE,CACtF,MAAO,CACL,OAAQ,EAAE,CACV,cAAe,EAAE,CAClB,CAWH,SAAgB,EACd,EACmB,CAEnB,IAAM,EAAQ,IAAI,IAElB,IAAK,GAAM,CAAC,EAAM,KAAc,OAAO,QAAQ,EAAgB,CAAE,CAC/D,IAAM,EAAc,IAAI,IACxB,IAAK,GAAM,CAAC,EAAU,KAAY,OAAO,QAAQ,EAAU,CACzD,EAAY,IAAI,EAAU,IAAI,IAAI,EAAQ,CAAC,CAE7C,EAAM,IAAI,EAAM,EAAY,CAG9B,OAAQ,EAAc,EAAkB,IAClC,IAAS,QAAgB,GACtB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QAAQ,EAAmB,CAC9C"}
@@ -0,0 +1,90 @@
1
+ import { Auth, BetterAuthPlugin } from "better-auth";
2
+ import { Plugin } from "@murumets-ee/core";
3
+ //#region src/types.d.ts
4
+ /**
5
+ * Auth plugin configuration
6
+ */
7
+ interface AuthConfig {
8
+ /** Auth providers to enable. Default: ['email'] */
9
+ providers?: ('email' | 'google' | 'github')[];
10
+ /** OAuth credentials (required when using social providers) */
11
+ social?: {
12
+ google?: {
13
+ clientId: string;
14
+ clientSecret: string;
15
+ };
16
+ github?: {
17
+ clientId: string;
18
+ clientSecret: string;
19
+ };
20
+ };
21
+ /** Session configuration */
22
+ session?: {
23
+ /** Session lifetime in seconds. Default: 7200 (2 hours) */expiresIn?: number; /** How often to refresh the session in seconds. Default: 3600 (1 hour) */
24
+ updateAge?: number;
25
+ };
26
+ /** Enable organization/multi-tenant support (maps to entity scope: 'team') */
27
+ organizations?: boolean;
28
+ /**
29
+ * Drizzle schema objects for the auth tables.
30
+ *
31
+ * Defaults to the canonical schema pre-baked in
32
+ * `@murumets-ee/auth/schema`. Override only if you're extending
33
+ * better-auth with custom plugins that add their own tables.
34
+ */
35
+ schema?: Record<string, unknown>;
36
+ /**
37
+ * Additional better-auth plugins to include.
38
+ * Use this for plugins not managed by the toolkit (e.g., twoFactor, magicLink).
39
+ */
40
+ betterAuthPlugins?: BetterAuthPlugin[];
41
+ /**
42
+ * Audit logging for auth events (login, signup, user update, ban, etc.).
43
+ * Enabled by default — writes to the toolkit_audit_logs table.
44
+ * Set to `false` to disable.
45
+ */
46
+ audit?: false;
47
+ }
48
+ //#endregion
49
+ //#region src/server.d.ts
50
+ /** Type of the auth server instance. Aliased from better-auth's generic
51
+ * `Auth` because the explicit annotation on `createAuthServer` means
52
+ * `ReturnType<typeof createAuthServer>` is already `BetterAuthBase`. */
53
+ type Auth$1 = Auth;
54
+ //#endregion
55
+ //#region src/plugin.d.ts
56
+ /**
57
+ * Get the auth server instance.
58
+ * Throws if the auth plugin hasn't been initialized yet.
59
+ *
60
+ * @example
61
+ * ```typescript
62
+ * // app/api/auth/[...all]/route.ts (user writes this)
63
+ * import { toNextJsHandler } from 'better-auth/next-js'
64
+ * import { getAuth } from '@murumets-ee/auth'
65
+ *
66
+ * export const { GET, POST } = toNextJsHandler(getAuth())
67
+ * ```
68
+ */
69
+ declare function getAuth(): Auth$1;
70
+ /**
71
+ * Create the auth toolkit plugin.
72
+ *
73
+ * @example
74
+ * ```typescript
75
+ * import { defineConfig } from '@murumets-ee/core'
76
+ * import { auth } from '@murumets-ee/auth'
77
+ *
78
+ * export default defineConfig({
79
+ * db: { url: process.env.DATABASE_URL! },
80
+ * entities: [Article, Category],
81
+ * plugins: [
82
+ * auth({ providers: ['email'] }),
83
+ * ],
84
+ * })
85
+ * ```
86
+ */
87
+ declare function auth(config?: AuthConfig): Plugin;
88
+ //#endregion
89
+ export { AuthConfig as i, getAuth as n, Auth$1 as r, auth as t };
90
+ //# sourceMappingURL=plugin-BS-ho4BN.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"plugin-BS-ho4BN.d.mts","names":[],"sources":["../src/types.ts","../src/server.ts","../src/plugin.ts"],"mappings":";;;;;;UAKiB,UAAA;EAAA;EAEf,SAAA;;EAGA,MAAA;IACE,MAAA;MAAW,QAAA;MAAkB,YAAA;IAAA;IAC7B,MAAA;MAAW,QAAA;MAAkB,YAAA;IAAA;EAAA;EAM7B;EAFF,OAAA;IAQA,2DANE,SAAA,WAeO;IAbP,SAAA;EAAA;EA0BF;EAtBA,aAAA;EAsBK;;;;AC4UP;;;EDzVE,MAAA,GAAS,MAAA;ECyVsB;;;;EDnV/B,iBAAA,GAAoB,gBAAA;EEFC;;;;AAwBvB;EFfE,KAAA;AAAA;;;AC4UF;;;AAAA,KAAY,MAAA,GAAO,IAAA;;;;;;;;;;;;;;;;iBCrVH,OAAA,CAAA,GAAW,MAAA;;;;;;;;;ADqV3B;;;;;;;;ACrVA;iBAwBgB,IAAA,CAAK,MAAA,GAAQ,UAAA,GAAkB,MAAA"}
@@ -0,0 +1,2 @@
1
+ import { n as getAuth, t as auth } from "./plugin-BS-ho4BN.mjs";
2
+ export { auth, getAuth };
@@ -0,0 +1,2 @@
1
+ import{a as e,f as t,m as n,r,s as i,t as a,u as o}from"./schema-Je6e5yt2.mjs";let s=null;function c(){if(!s)throw Error(`@murumets-ee/auth not initialized. Add auth() to your toolkit config plugins.`);return s}function l(c={}){return{name:`@murumets-ee/auth`,tables:{user:t,session:o,account:a,verification:n,organization:i,member:e,invitation:r},init:async e=>{let{createAuthServer:t}=await import(`./server-B7Gdv2He.mjs`),n;if(c.audit!==!1){let{createAuditLogger:t,createAuditDbWriter:r,createLogger:i}=await import(`@murumets-ee/logging`);n=t({logger:i({name:`auth-audit`}),dbWriter:r(e.db.readWrite)})}s=t(c,e,n),e.logger.info(`Auth plugin initialized`)}}}export{l as auth,c as getAuth};
2
+ //# sourceMappingURL=plugin.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"plugin.mjs","names":[],"sources":["../src/plugin.ts"],"sourcesContent":["/**\n * Toolkit plugin implementation for @murumets-ee/auth.\n *\n * Implements the Plugin interface from @murumets-ee/core.\n * Creates and stores the better-auth server instance during init.\n */\n\nimport type { Plugin } from '@murumets-ee/core'\nimport type { AuditLogger } from '@murumets-ee/logging'\nimport {\n account,\n invitation,\n member,\n organization,\n session,\n user,\n verification,\n} from './schema.js'\nimport type { Auth } from './server.js'\nimport type { AuthConfig } from './types.js'\n\n/** The initialized auth server instance (set during plugin init) */\nlet _auth: Auth | null = null\n\n/**\n * Get the auth server instance.\n * Throws if the auth plugin hasn't been initialized yet.\n *\n * @example\n * ```typescript\n * // app/api/auth/[...all]/route.ts (user writes this)\n * import { toNextJsHandler } from 'better-auth/next-js'\n * import { getAuth } from '@murumets-ee/auth'\n *\n * export const { GET, POST } = toNextJsHandler(getAuth())\n * ```\n */\nexport function getAuth(): Auth {\n if (!_auth) {\n throw new Error('@murumets-ee/auth not initialized. Add auth() to your toolkit config plugins.')\n }\n return _auth\n}\n\n/**\n * Create the auth toolkit plugin.\n *\n * @example\n * ```typescript\n * import { defineConfig } from '@murumets-ee/core'\n * import { auth } from '@murumets-ee/auth'\n *\n * export default defineConfig({\n * db: { url: process.env.DATABASE_URL! },\n * entities: [Article, Category],\n * plugins: [\n * auth({ providers: ['email'] }),\n * ],\n * })\n * ```\n */\nexport function auth(config: AuthConfig = {}): Plugin {\n return {\n name: '@murumets-ee/auth',\n // Expose better-auth's Drizzle tables so `lumi migrate` picks them up\n // automatically. The canonical schema lives in\n // `@murumets-ee/auth/schema` — committed, not codegen-generated.\n tables: { user, session, account, verification, organization, member, invitation },\n init: async (app) => {\n const { createAuthServer } = await import('./server.js')\n\n // Create audit logger for auth events (login, signup, ban, etc.)\n // unless explicitly disabled via `audit: false`\n let auditLogger: AuditLogger | undefined\n if (config.audit !== false) {\n const { createAuditLogger, createAuditDbWriter, createLogger } = await import(\n '@murumets-ee/logging'\n )\n auditLogger = createAuditLogger({\n logger: createLogger({ name: 'auth-audit' }),\n dbWriter: createAuditDbWriter(app.db.readWrite),\n })\n }\n\n _auth = createAuthServer(config, app, auditLogger)\n app.logger.info('Auth plugin initialized')\n },\n }\n}\n"],"mappings":"+EAsBA,IAAI,EAAqB,KAezB,SAAgB,GAAgB,CAC9B,GAAI,CAAC,EACH,MAAU,MAAM,gFAAgF,CAElG,OAAO,EAoBT,SAAgB,EAAK,EAAqB,EAAE,CAAU,CACpD,MAAO,CACL,KAAM,oBAIN,OAAQ,CAAE,OAAM,UAAS,UAAS,eAAc,eAAc,SAAQ,aAAY,CAClF,KAAM,KAAO,IAAQ,CACnB,GAAM,CAAE,oBAAqB,MAAM,OAAO,yBAItC,EACJ,GAAI,EAAO,QAAU,GAAO,CAC1B,GAAM,CAAE,oBAAmB,sBAAqB,gBAAiB,MAAM,OACrE,wBAEF,EAAc,EAAkB,CAC9B,OAAQ,EAAa,CAAE,KAAM,aAAc,CAAC,CAC5C,SAAU,EAAoB,EAAI,GAAG,UAAU,CAChD,CAAC,CAGJ,EAAQ,EAAiB,EAAQ,EAAK,EAAY,CAClD,EAAI,OAAO,KAAK,0BAA0B,EAE7C"}
@@ -0,0 +1,2 @@
1
+ import{relations as e}from"drizzle-orm";import{boolean as t,index as n,pgTable as r,text as i,timestamp as a,uniqueIndex as o}from"drizzle-orm/pg-core";var s=Object.defineProperty,c=((e,t)=>{let n={};for(var r in e)s(n,r,{get:e[r],enumerable:!0});return t||s(n,Symbol.toStringTag,{value:`Module`}),n})({account:()=>d,accountRelations:()=>v,invitation:()=>h,invitationRelations:()=>x,member:()=>m,memberRelations:()=>b,organization:()=>p,organizationRelations:()=>y,session:()=>u,sessionRelations:()=>_,user:()=>l,userRelations:()=>g,verification:()=>f});const l=r(`user`,{id:i(`id`).primaryKey(),name:i(`name`).notNull(),email:i(`email`).notNull().unique(),emailVerified:t(`email_verified`).default(!1).notNull(),image:i(`image`),createdAt:a(`created_at`).defaultNow().notNull(),updatedAt:a(`updated_at`).defaultNow().$onUpdate(()=>new Date).notNull(),role:i(`role`),banned:t(`banned`).default(!1),banReason:i(`ban_reason`),banExpires:a(`ban_expires`)}),u=r(`session`,{id:i(`id`).primaryKey(),expiresAt:a(`expires_at`).notNull(),token:i(`token`).notNull().unique(),createdAt:a(`created_at`).defaultNow().notNull(),updatedAt:a(`updated_at`).$onUpdate(()=>new Date).notNull(),ipAddress:i(`ip_address`),userAgent:i(`user_agent`),userId:i(`user_id`).notNull().references(()=>l.id,{onDelete:`cascade`}),impersonatedBy:i(`impersonated_by`),activeOrganizationId:i(`active_organization_id`)},e=>[n(`session_userId_idx`).on(e.userId)]),d=r(`account`,{id:i(`id`).primaryKey(),accountId:i(`account_id`).notNull(),providerId:i(`provider_id`).notNull(),userId:i(`user_id`).notNull().references(()=>l.id,{onDelete:`cascade`}),accessToken:i(`access_token`),refreshToken:i(`refresh_token`),idToken:i(`id_token`),accessTokenExpiresAt:a(`access_token_expires_at`),refreshTokenExpiresAt:a(`refresh_token_expires_at`),scope:i(`scope`),password:i(`password`),createdAt:a(`created_at`).defaultNow().notNull(),updatedAt:a(`updated_at`).$onUpdate(()=>new Date).notNull()},e=>[n(`account_userId_idx`).on(e.userId)]),f=r(`verification`,{id:i(`id`).primaryKey(),identifier:i(`identifier`).notNull(),value:i(`value`).notNull(),expiresAt:a(`expires_at`).notNull(),createdAt:a(`created_at`).defaultNow().notNull(),updatedAt:a(`updated_at`).defaultNow().$onUpdate(()=>new Date).notNull()},e=>[n(`verification_identifier_idx`).on(e.identifier)]),p=r(`organization`,{id:i(`id`).primaryKey(),name:i(`name`).notNull(),slug:i(`slug`).notNull().unique(),logo:i(`logo`),createdAt:a(`created_at`).notNull(),metadata:i(`metadata`)},e=>[o(`organization_slug_uidx`).on(e.slug)]),m=r(`member`,{id:i(`id`).primaryKey(),organizationId:i(`organization_id`).notNull().references(()=>p.id,{onDelete:`cascade`}),userId:i(`user_id`).notNull().references(()=>l.id,{onDelete:`cascade`}),role:i(`role`).default(`member`).notNull(),createdAt:a(`created_at`).notNull()},e=>[n(`member_organizationId_idx`).on(e.organizationId),n(`member_userId_idx`).on(e.userId)]),h=r(`invitation`,{id:i(`id`).primaryKey(),organizationId:i(`organization_id`).notNull().references(()=>p.id,{onDelete:`cascade`}),email:i(`email`).notNull(),role:i(`role`),status:i(`status`).default(`pending`).notNull(),expiresAt:a(`expires_at`).notNull(),createdAt:a(`created_at`).defaultNow().notNull(),inviterId:i(`inviter_id`).notNull().references(()=>l.id,{onDelete:`cascade`})},e=>[n(`invitation_organizationId_idx`).on(e.organizationId),n(`invitation_email_idx`).on(e.email)]),g=e(l,({many:e})=>({sessions:e(u),accounts:e(d),members:e(m),invitations:e(h)})),_=e(u,({one:e})=>({user:e(l,{fields:[u.userId],references:[l.id]})})),v=e(d,({one:e})=>({user:e(l,{fields:[d.userId],references:[l.id]})})),y=e(p,({many:e})=>({members:e(m),invitations:e(h)})),b=e(m,({one:e})=>({organization:e(p,{fields:[m.organizationId],references:[p.id]}),user:e(l,{fields:[m.userId],references:[l.id]})})),x=e(h,({one:e})=>({organization:e(p,{fields:[h.organizationId],references:[p.id]}),user:e(l,{fields:[h.inviterId],references:[l.id]})}));export{m as a,y as c,_ as d,l as f,x as i,c as l,f as m,v as n,b as o,g as p,h as r,p as s,d as t,u};
2
+ //# sourceMappingURL=schema-Je6e5yt2.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schema-Je6e5yt2.mjs","names":[],"sources":["../src/schema.ts"],"sourcesContent":["/**\n * Pre-generated Drizzle schema for better-auth tables.\n *\n * This file is the canonical snapshot of every table better-auth's\n * `admin` and `organization` plugins create when configured with the\n * toolkit's default server. It is committed source — NOT generated at\n * `lumi setup` time — so scaffolded projects don't need to invoke\n * `@better-auth/cli generate`, don't need a separate `auth.config.ts`,\n * and don't carry a `generated/auth-schema.ts` file in their repo.\n *\n * Regenerating this file:\n *\n * 1. Only when bumping better-auth or changing the plugin list in\n * `packages/auth/src/server.ts`.\n * 2. Run `pnpm --filter @murumets-ee/auth gen:schema` (which runs\n * `@better-auth/cli generate` against `scripts/schema-source.ts`)\n * and review the diff.\n * 3. Commit.\n *\n * Consumers: `import * as authSchema from '@murumets-ee/auth/schema'`\n * and pass it directly to drizzle-kit/api's `generateDrizzleJson`.\n */\n\nimport { relations } from 'drizzle-orm'\nimport { boolean, index, pgTable, text, timestamp, uniqueIndex } from 'drizzle-orm/pg-core'\n\nexport const user = pgTable('user', {\n id: text('id').primaryKey(),\n name: text('name').notNull(),\n email: text('email').notNull().unique(),\n emailVerified: boolean('email_verified').default(false).notNull(),\n image: text('image'),\n createdAt: timestamp('created_at').defaultNow().notNull(),\n updatedAt: timestamp('updated_at')\n .defaultNow()\n .$onUpdate(() => /* @__PURE__ */ new Date())\n .notNull(),\n role: text('role'),\n banned: boolean('banned').default(false),\n banReason: text('ban_reason'),\n banExpires: timestamp('ban_expires'),\n})\n\nexport const session = pgTable(\n 'session',\n {\n id: text('id').primaryKey(),\n expiresAt: timestamp('expires_at').notNull(),\n token: text('token').notNull().unique(),\n createdAt: timestamp('created_at').defaultNow().notNull(),\n updatedAt: timestamp('updated_at')\n .$onUpdate(() => /* @__PURE__ */ new Date())\n .notNull(),\n ipAddress: text('ip_address'),\n userAgent: text('user_agent'),\n userId: text('user_id')\n .notNull()\n .references(() => user.id, { onDelete: 'cascade' }),\n impersonatedBy: text('impersonated_by'),\n activeOrganizationId: text('active_organization_id'),\n },\n (table) => [index('session_userId_idx').on(table.userId)],\n)\n\nexport const account = pgTable(\n 'account',\n {\n id: text('id').primaryKey(),\n accountId: text('account_id').notNull(),\n providerId: text('provider_id').notNull(),\n userId: text('user_id')\n .notNull()\n .references(() => user.id, { onDelete: 'cascade' }),\n accessToken: text('access_token'),\n refreshToken: text('refresh_token'),\n idToken: text('id_token'),\n accessTokenExpiresAt: timestamp('access_token_expires_at'),\n refreshTokenExpiresAt: timestamp('refresh_token_expires_at'),\n scope: text('scope'),\n password: text('password'),\n createdAt: timestamp('created_at').defaultNow().notNull(),\n updatedAt: timestamp('updated_at')\n .$onUpdate(() => /* @__PURE__ */ new Date())\n .notNull(),\n },\n (table) => [index('account_userId_idx').on(table.userId)],\n)\n\nexport const verification = pgTable(\n 'verification',\n {\n id: text('id').primaryKey(),\n identifier: text('identifier').notNull(),\n value: text('value').notNull(),\n expiresAt: timestamp('expires_at').notNull(),\n createdAt: timestamp('created_at').defaultNow().notNull(),\n updatedAt: timestamp('updated_at')\n .defaultNow()\n .$onUpdate(() => /* @__PURE__ */ new Date())\n .notNull(),\n },\n (table) => [index('verification_identifier_idx').on(table.identifier)],\n)\n\nexport const organization = pgTable(\n 'organization',\n {\n id: text('id').primaryKey(),\n name: text('name').notNull(),\n slug: text('slug').notNull().unique(),\n logo: text('logo'),\n createdAt: timestamp('created_at').notNull(),\n metadata: text('metadata'),\n },\n (table) => [uniqueIndex('organization_slug_uidx').on(table.slug)],\n)\n\nexport const member = pgTable(\n 'member',\n {\n id: text('id').primaryKey(),\n organizationId: text('organization_id')\n .notNull()\n .references(() => organization.id, { onDelete: 'cascade' }),\n userId: text('user_id')\n .notNull()\n .references(() => user.id, { onDelete: 'cascade' }),\n role: text('role').default('member').notNull(),\n createdAt: timestamp('created_at').notNull(),\n },\n (table) => [\n index('member_organizationId_idx').on(table.organizationId),\n index('member_userId_idx').on(table.userId),\n ],\n)\n\nexport const invitation = pgTable(\n 'invitation',\n {\n id: text('id').primaryKey(),\n organizationId: text('organization_id')\n .notNull()\n .references(() => organization.id, { onDelete: 'cascade' }),\n email: text('email').notNull(),\n role: text('role'),\n status: text('status').default('pending').notNull(),\n expiresAt: timestamp('expires_at').notNull(),\n createdAt: timestamp('created_at').defaultNow().notNull(),\n inviterId: text('inviter_id')\n .notNull()\n .references(() => user.id, { onDelete: 'cascade' }),\n },\n (table) => [\n index('invitation_organizationId_idx').on(table.organizationId),\n index('invitation_email_idx').on(table.email),\n ],\n)\n\nexport const userRelations = relations(user, ({ many }) => ({\n sessions: many(session),\n accounts: many(account),\n members: many(member),\n invitations: many(invitation),\n}))\n\nexport const sessionRelations = relations(session, ({ one }) => ({\n user: one(user, {\n fields: [session.userId],\n references: [user.id],\n }),\n}))\n\nexport const accountRelations = relations(account, ({ one }) => ({\n user: one(user, {\n fields: [account.userId],\n references: [user.id],\n }),\n}))\n\nexport const organizationRelations = relations(organization, ({ many }) => ({\n members: many(member),\n invitations: many(invitation),\n}))\n\nexport const memberRelations = relations(member, ({ one }) => ({\n organization: one(organization, {\n fields: [member.organizationId],\n references: [organization.id],\n }),\n user: one(user, {\n fields: [member.userId],\n references: [user.id],\n }),\n}))\n\nexport const invitationRelations = relations(invitation, ({ one }) => ({\n organization: one(organization, {\n fields: [invitation.organizationId],\n references: [organization.id],\n }),\n user: one(user, {\n fields: [invitation.inviterId],\n references: [user.id],\n }),\n}))\n"],"mappings":"0iBA0BA,MAAa,EAAO,EAAQ,OAAQ,CAClC,GAAI,EAAK,KAAK,CAAC,YAAY,CAC3B,KAAM,EAAK,OAAO,CA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