@lunora/auth 1.0.0-alpha.266 → 1.0.0-alpha.267

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.
package/dist/index.d.mts CHANGED
@@ -231,13 +231,24 @@ declare const buildAuditEntry: (context: AuditHookContext, { now, trustProxyHead
231
231
  */
232
232
  declare const authAuditHook: (config: AuthAuditHookConfig) => ReturnType<typeof createAuthMiddleware>;
233
233
  /**
234
- * Merge the audit `hooks.after` middleware into a better-auth options object,
235
- * composing with any `hooks.after` the caller already set (theirs runs first,
236
- * then the audit record). Returns a new options object.
234
+ * Create the better-auth `hooks.before` middleware that reads what an audited endpoint
235
+ * destroys: the owner of the session `/admin/revoke-user-session` deletes, so the
236
+ * {@link authAuditHook} row can name the user as `detail.targetUserId`. Only the user id is
237
+ * kept, never the session token. Install it as `hooks.before` next to `authAuditHook`, or let
238
+ * {@link withAuthAudit} install both.
239
+ */
240
+ declare const authAuditBeforeHook: () => ReturnType<typeof createAuthMiddleware>;
241
+ /**
242
+ * Merge the audit middleware into a better-auth options object: `hooks.before`
243
+ * reads what a revoke is about to delete, then `hooks.after` records the row.
244
+ * Each composes with the hook the caller already set: the audit's before hook
245
+ * runs ahead of the caller's, which may end the request, and the caller's after
246
+ * hook runs ahead of the audit record. Returns a new options object.
237
247
  */
238
248
  declare const withAuthAudit: <Options extends {
239
249
  hooks?: {
240
250
  after?: unknown;
251
+ before?: unknown;
241
252
  };
242
253
  }>(options: Options, config: AuthAuditHookConfig) => Options;
243
254
  /**
@@ -489,4 +500,4 @@ declare const validateSessionPolicy: (policy: SessionPolicy) => SessionPolicy;
489
500
  * with the same 60s cookie cache as `rolling`.
490
501
  */
491
502
  declare const sessionPresets: Record<"longLived" | "rolling" | "strict", SessionPolicy>;
492
- export { READ_AUDIT_PATH as AUTH_DO_AUDIT_PATH, INTERNAL_SECRET_HEADER as AUTH_DO_SECRET_HEADER, RESOLVE_SESSION_PATH as AUTH_DO_SESSION_PATH, type AppendAuthAuditEntry, type AppendAuthAuditOptions, type AuthAuditEvent, type AuthAuditHookConfig, type AuthDoOptions, type AuthDoState, DEFAULT_AUTH_BASE_PATH, type EmailClassification, type EmailGateConfig, type EmailGateHookConfig, LunoraAuthDO, type LunoraAuthOptions, type SessionPolicy, type SqlExecutor, authAuditHook, authDoColumnAdditions, authDoSchemaStatements, buildAuditEntry, emailGateDatabaseHooks, eventForPath, isDevEnvironment, legacyIssuerCleanupStatements, sessionPresets, validateSessionPolicy, withAuthAudit, withEmailGate };
503
+ export { READ_AUDIT_PATH as AUTH_DO_AUDIT_PATH, INTERNAL_SECRET_HEADER as AUTH_DO_SECRET_HEADER, RESOLVE_SESSION_PATH as AUTH_DO_SESSION_PATH, type AppendAuthAuditEntry, type AppendAuthAuditOptions, type AuthAuditEvent, type AuthAuditHookConfig, type AuthDoOptions, type AuthDoState, DEFAULT_AUTH_BASE_PATH, type EmailClassification, type EmailGateConfig, type EmailGateHookConfig, LunoraAuthDO, type LunoraAuthOptions, type SessionPolicy, type SqlExecutor, authAuditBeforeHook, authAuditHook, authDoColumnAdditions, authDoSchemaStatements, buildAuditEntry, emailGateDatabaseHooks, eventForPath, isDevEnvironment, legacyIssuerCleanupStatements, sessionPresets, validateSessionPolicy, withAuthAudit, withEmailGate };
package/dist/index.d.ts CHANGED
@@ -231,13 +231,24 @@ declare const buildAuditEntry: (context: AuditHookContext, { now, trustProxyHead
231
231
  */
232
232
  declare const authAuditHook: (config: AuthAuditHookConfig) => ReturnType<typeof createAuthMiddleware>;
233
233
  /**
234
- * Merge the audit `hooks.after` middleware into a better-auth options object,
235
- * composing with any `hooks.after` the caller already set (theirs runs first,
236
- * then the audit record). Returns a new options object.
234
+ * Create the better-auth `hooks.before` middleware that reads what an audited endpoint
235
+ * destroys: the owner of the session `/admin/revoke-user-session` deletes, so the
236
+ * {@link authAuditHook} row can name the user as `detail.targetUserId`. Only the user id is
237
+ * kept, never the session token. Install it as `hooks.before` next to `authAuditHook`, or let
238
+ * {@link withAuthAudit} install both.
239
+ */
240
+ declare const authAuditBeforeHook: () => ReturnType<typeof createAuthMiddleware>;
241
+ /**
242
+ * Merge the audit middleware into a better-auth options object: `hooks.before`
243
+ * reads what a revoke is about to delete, then `hooks.after` records the row.
244
+ * Each composes with the hook the caller already set: the audit's before hook
245
+ * runs ahead of the caller's, which may end the request, and the caller's after
246
+ * hook runs ahead of the audit record. Returns a new options object.
237
247
  */
238
248
  declare const withAuthAudit: <Options extends {
239
249
  hooks?: {
240
250
  after?: unknown;
251
+ before?: unknown;
241
252
  };
242
253
  }>(options: Options, config: AuthAuditHookConfig) => Options;
243
254
  /**
@@ -489,4 +500,4 @@ declare const validateSessionPolicy: (policy: SessionPolicy) => SessionPolicy;
489
500
  * with the same 60s cookie cache as `rolling`.
490
501
  */
491
502
  declare const sessionPresets: Record<"longLived" | "rolling" | "strict", SessionPolicy>;
492
- export { READ_AUDIT_PATH as AUTH_DO_AUDIT_PATH, INTERNAL_SECRET_HEADER as AUTH_DO_SECRET_HEADER, RESOLVE_SESSION_PATH as AUTH_DO_SESSION_PATH, type AppendAuthAuditEntry, type AppendAuthAuditOptions, type AuthAuditEvent, type AuthAuditHookConfig, type AuthDoOptions, type AuthDoState, DEFAULT_AUTH_BASE_PATH, type EmailClassification, type EmailGateConfig, type EmailGateHookConfig, LunoraAuthDO, type LunoraAuthOptions, type SessionPolicy, type SqlExecutor, authAuditHook, authDoColumnAdditions, authDoSchemaStatements, buildAuditEntry, emailGateDatabaseHooks, eventForPath, isDevEnvironment, legacyIssuerCleanupStatements, sessionPresets, validateSessionPolicy, withAuthAudit, withEmailGate };
503
+ export { READ_AUDIT_PATH as AUTH_DO_AUDIT_PATH, INTERNAL_SECRET_HEADER as AUTH_DO_SECRET_HEADER, RESOLVE_SESSION_PATH as AUTH_DO_SESSION_PATH, type AppendAuthAuditEntry, type AppendAuthAuditOptions, type AuthAuditEvent, type AuthAuditHookConfig, type AuthDoOptions, type AuthDoState, DEFAULT_AUTH_BASE_PATH, type EmailClassification, type EmailGateConfig, type EmailGateHookConfig, LunoraAuthDO, type LunoraAuthOptions, type SessionPolicy, type SqlExecutor, authAuditBeforeHook, authAuditHook, authDoColumnAdditions, authDoSchemaStatements, buildAuditEntry, emailGateDatabaseHooks, eventForPath, isDevEnvironment, legacyIssuerCleanupStatements, sessionPresets, validateSessionPolicy, withAuthAudit, withEmailGate };
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{l as r,a as o,b as a}from"./packem_shared/adapter-CBZ17jKi.mjs";import{LunoraAuthAdminError as s,createAuthAdmin as u}from"./packem_shared/LunoraAuthAdminError-D5RhUgha.mjs";import{AUTH_AUDIT_TABLE as A,appendAuthAuditEntry as m,createAuthAuditReader as p,ensureAuthAuditTable as h,readAuthAuditLog as l}from"./audit.mjs";import{authAuditHook as f,buildAuditEntry as x,eventForPath as E,withAuthAudit as D}from"./packem_shared/authAuditHook-By12zXDV.mjs";import{R as S,I as c,a as v,L as _}from"./packem_shared/auth-do-vDGawDob.mjs";import{createAuth as U,resolveAuthOptions as y}from"./packem_shared/createAuth-Dioo_-mD.mjs";import{authDiscoveryPaths as P,authDiscoveryPathsFor as L,handleAuthDiscoveryRequest as g}from"./packem_shared/authDiscoveryPaths-BtKCs_3V.mjs";import{authDoColumnAdditions as O,authDoSchemaStatements as w}from"./packem_shared/authDoColumnAdditions-UwF3Rl41.mjs";import{createDoAuthWiring as F}from"./packem_shared/createDoAuthWiring-Te19LXi-.mjs";import{emailGateDatabaseHooks as k,withEmailGate as q}from"./packem_shared/emailGateDatabaseHooks-Dvyliwxx.mjs";import{assertEmailAllowed as G,classifyEmail as M,emailGateMiddleware as B,loadEmailDomainLists as W}from"./email-guard.mjs";import{default as Y}from"./packem_shared/isDevEnvironment-yLbPngwn.mjs";import{handleAuthRequest as z}from"./packem_shared/handleAuthRequest-Id9Vv_Tk.mjs";import{createSignUpInvitation as K,listSignUpInvitations as Q,pruneSignUpInvitations as X,revokeSignUpInvitation as Z}from"./packem_shared/createSignUpInvitation-CwrPh0XH.mjs";import{legacyIssuerCleanupStatements as tt}from"./packem_shared/legacyIssuerCleanupStatements-D9Kf8OD1.mjs";import{LunoraAuthHeadersError as rt,withAuthPlugins as ot}from"./middleware.mjs";import{default as it}from"./schema.mjs";import{sessionPresets as ut,validateSessionPolicy as nt}from"./packem_shared/sessionPresets-C867Mlo4.mjs";import{resolveSessionIdentity as mt}from"./packem_shared/resolveSessionIdentity-CNjGy6Pb.mjs";import{c as ht,d as lt}from"./packem_shared/sql-store-uMubPYI9.mjs";import{createMemoryAuthStore as ft,matchesWhere as xt}from"./store.mjs";import{TURNSTILE_VERIFY_ENDPOINT as Dt,verifyTurnstile as Tt}from"./turnstile.mjs";import{verifyTurnstileMiddleware as ct}from"./turnstile-middleware.mjs";import{DEFAULT_AUTH_BASE_PATH as _t}from"./packem_shared/DEFAULT_AUTH_BASE_PATH-C3SqYG3N.mjs";export{A as AUTH_AUDIT_TABLE,S as AUTH_DO_AUDIT_PATH,c as AUTH_DO_SECRET_HEADER,v as AUTH_DO_SESSION_PATH,_t as DEFAULT_AUTH_BASE_PATH,s as LunoraAuthAdminError,_ as LunoraAuthDO,rt as LunoraAuthHeadersError,Dt as TURNSTILE_VERIFY_ENDPOINT,m as appendAuthAuditEntry,G as assertEmailAllowed,f as authAuditHook,P as authDiscoveryPaths,L as authDiscoveryPathsFor,O as authDoColumnAdditions,w as authDoSchemaStatements,it as authTables,x as buildAuditEntry,M as classifyEmail,U as createAuth,u as createAuthAdmin,p as createAuthAuditReader,F as createDoAuthWiring,ft as createMemoryAuthStore,K as createSignUpInvitation,ht as createSqlAuthStore,lt as d1Executor,k as emailGateDatabaseHooks,B as emailGateMiddleware,h as ensureAuthAuditTable,E as eventForPath,g as handleAuthDiscoveryRequest,z as handleAuthRequest,Y as isDevEnvironment,tt as legacyIssuerCleanupStatements,Q as listSignUpInvitations,W as loadEmailDomainLists,r as lunoraAuthAdapter,o as lunoraD1Adapter,a as lunoraDoAdapter,xt as matchesWhere,X as pruneSignUpInvitations,l as readAuthAuditLog,y as resolveAuthOptions,mt as resolveSessionIdentity,Z as revokeSignUpInvitation,ut as sessionPresets,nt as validateSessionPolicy,Tt as verifyTurnstile,ct as verifyTurnstileMiddleware,D as withAuthAudit,ot as withAuthPlugins,q as withEmailGate};
1
+ import{l as r,a as o,b as a}from"./packem_shared/adapter-CBZ17jKi.mjs";import{LunoraAuthAdminError as s,createAuthAdmin as u}from"./packem_shared/LunoraAuthAdminError-D5RhUgha.mjs";import{AUTH_AUDIT_TABLE as n,appendAuthAuditEntry as m,createAuthAuditReader as h,ensureAuthAuditTable as p,readAuthAuditLog as l}from"./audit.mjs";import{authAuditBeforeHook as f,authAuditHook as x,buildAuditEntry as E,eventForPath as D,withAuthAudit as T}from"./packem_shared/authAuditBeforeHook-CQxnNVQq.mjs";import{R as c,I as v,a as _,L as H}from"./packem_shared/auth-do-vDGawDob.mjs";import{createAuth as U,resolveAuthOptions as y}from"./packem_shared/createAuth-Dioo_-mD.mjs";import{authDiscoveryPaths as L,authDiscoveryPathsFor as g,handleAuthDiscoveryRequest as R}from"./packem_shared/authDiscoveryPaths-BtKCs_3V.mjs";import{authDoColumnAdditions as w,authDoSchemaStatements as b}from"./packem_shared/authDoColumnAdditions-UwF3Rl41.mjs";import{createDoAuthWiring as F}from"./packem_shared/createDoAuthWiring-Te19LXi-.mjs";import{emailGateDatabaseHooks as q,withEmailGate as B}from"./packem_shared/emailGateDatabaseHooks-Dvyliwxx.mjs";import{assertEmailAllowed as G,classifyEmail as M,emailGateMiddleware as W,loadEmailDomainLists as V}from"./email-guard.mjs";import{default as j}from"./packem_shared/isDevEnvironment-yLbPngwn.mjs";import{handleAuthRequest as J}from"./packem_shared/handleAuthRequest-Id9Vv_Tk.mjs";import{createSignUpInvitation as Q,listSignUpInvitations as X,pruneSignUpInvitations as Z,revokeSignUpInvitation as $}from"./packem_shared/createSignUpInvitation-CwrPh0XH.mjs";import{legacyIssuerCleanupStatements as et}from"./packem_shared/legacyIssuerCleanupStatements-D9Kf8OD1.mjs";import{LunoraAuthHeadersError as ot,withAuthPlugins as at}from"./middleware.mjs";import{default as st}from"./schema.mjs";import{sessionPresets as At,validateSessionPolicy as nt}from"./packem_shared/sessionPresets-C867Mlo4.mjs";import{resolveSessionIdentity as ht}from"./packem_shared/resolveSessionIdentity-CNjGy6Pb.mjs";import{c as lt,d as dt}from"./packem_shared/sql-store-uMubPYI9.mjs";import{createMemoryAuthStore as xt,matchesWhere as Et}from"./store.mjs";import{TURNSTILE_VERIFY_ENDPOINT as Tt,verifyTurnstile as St}from"./turnstile.mjs";import{verifyTurnstileMiddleware as vt}from"./turnstile-middleware.mjs";import{DEFAULT_AUTH_BASE_PATH as Ht}from"./packem_shared/DEFAULT_AUTH_BASE_PATH-C3SqYG3N.mjs";export{n as AUTH_AUDIT_TABLE,c as AUTH_DO_AUDIT_PATH,v as AUTH_DO_SECRET_HEADER,_ as AUTH_DO_SESSION_PATH,Ht as DEFAULT_AUTH_BASE_PATH,s as LunoraAuthAdminError,H as LunoraAuthDO,ot as LunoraAuthHeadersError,Tt as TURNSTILE_VERIFY_ENDPOINT,m as appendAuthAuditEntry,G as assertEmailAllowed,f as authAuditBeforeHook,x as authAuditHook,L as authDiscoveryPaths,g as authDiscoveryPathsFor,w as authDoColumnAdditions,b as authDoSchemaStatements,st as authTables,E as buildAuditEntry,M as classifyEmail,U as createAuth,u as createAuthAdmin,h as createAuthAuditReader,F as createDoAuthWiring,xt as createMemoryAuthStore,Q as createSignUpInvitation,lt as createSqlAuthStore,dt as d1Executor,q as emailGateDatabaseHooks,W as emailGateMiddleware,p as ensureAuthAuditTable,D as eventForPath,R as handleAuthDiscoveryRequest,J as handleAuthRequest,j as isDevEnvironment,et as legacyIssuerCleanupStatements,X as listSignUpInvitations,V as loadEmailDomainLists,r as lunoraAuthAdapter,o as lunoraD1Adapter,a as lunoraDoAdapter,Et as matchesWhere,Z as pruneSignUpInvitations,l as readAuthAuditLog,y as resolveAuthOptions,ht as resolveSessionIdentity,$ as revokeSignUpInvitation,At as sessionPresets,nt as validateSessionPolicy,St as verifyTurnstile,vt as verifyTurnstileMiddleware,T as withAuthAudit,at as withAuthPlugins,B as withEmailGate};
@@ -0,0 +1 @@
1
+ import{decodeBasicCredentials as _}from"@better-auth/core/oauth2";import{cyrb53 as O}from"@lunora/values";import{createAuthMiddleware as I}from"better-auth/api";import{o as A}from"./on-cloudflare-edge-Dx6gFjBO.mjs";import{appendAuthAuditEntry as C}from"../audit.mjs";const W=[["/admin/impersonate-user","admin-impersonate-start"],["/admin/stop-impersonating","admin-impersonate-stop"],["/admin/set-user-password","admin-password-set"],["/admin/set-role","admin-role-change"],["/admin/revoke-user-session","admin-session-revoke"],["/admin/revoke-user-sessions","admin-session-revoke"],["/admin/ban-user","admin-user-ban"],["/admin/unban-user","admin-user-unban"],["/admin/create-user","admin-user-create"],["/admin/update-user","admin-user-update"],["/admin/remove-user","admin-user-remove"],["/api-key/create","api-key-create"],["/api-key/update","api-key-update"],["/api-key/delete","api-key-delete"],["/device/approve","device-approve"],["/device/deny","device-deny"],["/device/token","sign-in"],["/email-otp/change-email","email-change"],["/email-otp/request-email-change","email-change-request"],["/change-email","email-change-request"],["/delete-user","user-delete"],["/delete-user/callback","user-delete"],["/delete-anonymous-user","user-delete"],["/forget-password/email-otp","password-reset-request"],["/email-otp/send-verification-otp","password-reset-request"],["/two-factor/generate-backup-codes","mfa-backup-codes-regenerate"],["/one-time-token/generate","one-time-token-create"],["/one-time-token/verify","sign-in"],["/one-tap/callback","sign-in"],["/passkey/verify-authentication","sign-in"],["/passkey/verify-registration","passkey-add"],["/passkey/delete-passkey","passkey-remove"],["/passkey/update-passkey","passkey-rename"],["/phone-number/verify","sign-in"],["/siwe/verify","sign-in"],["/sso/callback","sign-in"],["/multi-session/set-active","session-switch"],["/multi-session/revoke","session-revoke"],["/oauth2/create-client","oauth-client-create"],["/oauth2/register","oauth-client-create"],["/oauth2/update-client","oauth-client-update"],["/oauth2/delete-client","oauth-client-delete"],["/oauth2/client/rotate-keys","oauth-client-keys-rotate"],["/oauth2/client/rotate-secret","oauth-client-secret-rotate"],["/oauth2/consent","oauth-consent"],["/oauth2/update-consent","oauth-consent-update"],["/oauth2/delete-consent","oauth-consent-revoke"],["/oauth2/revoke","oauth-token-revoke"],["/oauth2/token","oauth-token-issue"],["/oauth2/end-session","sign-out"],["/oauth2/end-session/confirm","sign-out"],["/organization/create","org-create"],["/organization/update","org-update"],["/organization/delete","org-delete"],["/organization/invite-member","org-invitation-create"],["/organization/accept-invitation","org-invitation-accept"],["/organization/reject-invitation","org-invitation-reject"],["/organization/cancel-invitation","org-invitation-cancel"],["/organization/leave","org-member-leave"],["/organization/remove-member","org-member-remove"],["/organization/update-member-role","org-member-role-change"],["/organization/set-active","org-switch"],["/organization/set-active-team","org-team-switch"],["/organization/create-role","org-role-change"],["/organization/update-role","org-role-change"],["/organization/delete-role","org-role-change"],["/organization/create-team","org-team-create"],["/organization/update-team","org-team-update"],["/organization/remove-team","org-team-remove"],["/organization/add-team-member","org-team-member-add"],["/organization/remove-team-member","org-team-member-remove"],["/sso/register","sso-provider-register"],["/sso/update-provider","sso-provider-update"],["/sso/delete-provider","sso-provider-delete"]],y=e=>new RegExp(`${e.split("/").map(t=>t.startsWith(":")?"[^/]+":t.toLowerCase().replaceAll(/[.*+?^${}()|[\]\\]/g,String.raw`\$&`)).join("/")}$`),z=[["POST","/admin/oauth2/resources","oauth-resource-create"],["PATCH","/admin/oauth2/resources/:identifier","oauth-resource-update"],["DELETE","/admin/oauth2/resources/:identifier","oauth-resource-delete"],["POST","/admin/oauth2/resources/:identifier/clients/:client_id","oauth-resource-client-link"],["DELETE","/admin/oauth2/resources/:identifier/clients/:client_id","oauth-resource-client-unlink"],["POST","/scim/v2/Users","scim-user-create"],["PATCH","/scim/v2/Users/:userId","scim-user-update"],["PUT","/scim/v2/Users/:userId","scim-user-update"],["DELETE","/scim/v2/Users/:userId","scim-user-delete"],["POST","/scim/v2/Groups","scim-group-create"],["PATCH","/scim/v2/Groups/:groupId","scim-group-update"],["PUT","/scim/v2/Groups/:groupId","scim-group-update"],["DELETE","/scim/v2/Groups/:groupId","scim-group-delete"]],P=W.map(([e,t])=>({event:t,pattern:y(e)})),L=z.map(([e,t,r])=>({event:r,method:e,pattern:y(t)})),R=e=>{const t=r=>e===r||e.endsWith(r);if(t("/sign-up/email")||t("/sign-up"))return"sign-up";if(t("/sign-in/social")||t("/sign-in/magic-link")||t("/sign-in/sso"))return"sign-in-initiated";if(e.includes("/sign-in/")||e.includes("/callback/")||e.includes("/saml2/sp/acs/")||t("/magic-link/verify")||e.includes("/two-factor/verify-"))return"sign-in";if(t("/sign-out")||e.includes("/saml2/logout/")||e.includes("/saml2/sp/slo/"))return"sign-out";if(t("/change-password")||t("/set-password"))return"password-change";if(t("/reset-password"))return"password-reset";if(t("/request-password-reset")||t("/forget-password"))return"password-reset-request";if(t("/verify-email"))return"email-verification";if(e.includes("/two-factor/enable")||e.includes("/totp/enable"))return"mfa-enable";if(e.includes("/two-factor/disable")||e.includes("/totp/disable"))return"mfa-disable";if(t("/refresh-token")||t("/token"))return"token-refresh";if(t("/revoke-session")||t("/revoke-sessions")||t("/revoke-other-sessions"))return"session-revoke";if(t("/link-social"))return"account-link";if(t("/unlink-account"))return"account-unlink"},b=(e,t,r)=>{const i=e.toLowerCase(),n=t?.toUpperCase(),a=i.includes("/callback/")||i.includes("/saml2/sp/acs/"),d=a?"sign-in":void 0,u=(i.endsWith("/oauth2/token")&&r==="refresh_token"?"token-refresh":void 0)??L.find(m=>m.method===n&&m.pattern.test(i))?.event??(a?void 0:P.find(m=>m.pattern.test(i))?.event)??R(i);return d??u},g=(e,t)=>e.headers?.get(t)??e.request?.headers.get(t)??void 0,U=(e,t)=>{if(A()){const r=g(e,"cf-connecting-ip");if(r!==void 0)return r}if(t===!0)return g(e,"x-forwarded-for")?.split(",")[0]?.trim()},l=e=>typeof e=="string"&&e.length>0?e:void 0,f=256,E=e=>e.length<=f?e:`${e.slice(0,f-15)}~${O(e).toString(16).padStart(14,"0")}`,o=e=>{const t=l(e);if(!(t===void 0||t.includes("@")))return E(t)},s=(e,t)=>typeof e=="object"&&e!==null&&t in e?e[t]:void 0,w=(e,t)=>{const r=e.context?.session,i=e.context?.newSession;return t==="session-revoke"||t==="session-switch"||t==="email-change"?r??i:i??r},D=(e,t)=>{const r=w(e,t),i=l(r?.session?.impersonatedBy);if(i!==void 0)return{actorId:i};const n=r?.user?.id??r?.session?.userId,a=r?.user?.email;return{...n===void 0?{}:{actorId:n},...a===void 0?{}:{actorEmail:a}}},h=e=>{const t=e.context?.returned;if(t instanceof Error)return"failure";if(typeof t=="object"&&t!==null&&"status"in t){const r=Number(t.status);if(Number.isFinite(r)&&r>=400)return"failure"}return"success"},v=320,N=(e,t)=>{if(t!=="sign-in"&&t!=="sign-in-initiated")return;const r=e.body?.email??e.body?.username;if(!(typeof r!="string"||r.length===0))return r.length>v?r.slice(0,v):r},H=(e,t)=>{const r=w(e,t);if(l(r?.session?.impersonatedBy)!==void 0)return l(r?.user?.id)},T=new WeakMap,q=(e,t)=>{if(t==="admin-session-revoke")return e.context===void 0?void 0:T.get(e.context);if(t==="admin-user-create")return o(s(s(e.context?.returned,"user"),"id"));if(t==="admin-impersonate-stop")return o(s(s(e.context?.session,"user"),"id"))??o(s(s(e.context?.session,"session"),"userId"))},M=e=>{const t=l(e.body?.newEmail)?.toLowerCase();return t!==void 0&&e.context?.newSession?.user?.email===t},F=/\.oauth_logout_confirmation=[^;]/u,G=e=>(e.context?.responseHeaders?.getSetCookie()??[]).some(t=>F.test(t)),j=new Set(["authorization_pending","slow_down"]),B=(e,t,r)=>{let i=t;return t==="email-change-request"&&r.endsWith("/change-email")&&M(e)?i="email-change":t==="sign-out"&&r.endsWith("/oauth2/end-session")&&G(e)?i=void 0:t==="password-reset-request"&&r.endsWith("/email-otp/send-verification-otp")&&(i=e.body?.type==="forget-password"?t:void 0),i},V=(e,t)=>{const r=e.path?.toLowerCase()??"",i=e.context?.returned,n=j.has(l(s(s(i,"body"),"error"))??"");let a;if(t==="sign-in"&&r.endsWith("/phone-number/verify")){const d=l(s(i,"token"))!==void 0;a=e.body?.updatePhoneNumber!==!0&&(d||h(e)==="failure")?"sign-in":"phone-verification"}else t==="user-delete"&&r.endsWith("/delete-user")&&l(s(i,"message"))==="Verification email sent"?a="user-delete-request":t==="sign-in"&&r.endsWith("/device/token")&&n?a=void 0:a=B(e,t,r);return a},$=e=>{if(typeof e=="string")return o(new URLSearchParams(e).get("client_id")??void 0)},X=/^basic /iu,k=(e,t)=>{if(!t.startsWith("org-invitation-"))return;const r=e.context?.returned;return o(s(s(r,"invitation"),"organizationId"))??o(s(s(r,"member"),"organizationId"))??(t==="org-invitation-cancel"?o(s(r,"organizationId")):void 0)},K=(e,t)=>t==="org-switch"?o(s(e.context?.returned,"id")):void 0,Y=/^[^?#]*/u,J=new Set(["did:","urn:"]),Q=e=>{const t=l(e);if(t!==void 0)try{const r=new URL(t);r.username="",r.password="",r.search="",r.hash="";const i=r.pathname==="/"?r.href.slice(0,-1):r.href;return r.host===""?J.has(r.protocol)?o(i):void 0:E(i)}catch{return o(Y.exec(t)?.[0])}},S=e=>{if(!(e===void 0||!X.test(e)))try{return o(_(e).clientId)}catch{return}},Z=(e,t)=>t==="oauth-client-create"&&h(e)==="success"?o(s(e.context?.returned,"client_id")):void 0,x=e=>Array.isArray(e)?o(e.every(t=>typeof t=="string")?e.join(","):void 0):o(e),ee=(e,t,r,i,n)=>t==="org-create"?i:t==="org-team-switch"?n:t==="org-team-update"?o(s(r.data,"organizationId"))??n:t.startsWith("org-team-")&&t!=="org-team-create"?o(r.organizationId)??n:t==="org-invitation-accept"||t==="org-invitation-reject"||t==="org-invitation-cancel"?k(e,t):o(r.organizationId)??o(s(e.context?.returned,"organizationId"))??k(e,t)??K(e,t)??n,te=(e,t)=>{const r=e.body??{},i=o(s(e.context?.returned,"id")),n=t.startsWith("org-member-")||t.startsWith("org-team-")||t==="org-role-change"||t==="org-update"||t==="org-invitation-create"?o(s(s(e.context?.session,"session"),"activeOrganizationId")):void 0,a=c=>typeof c=="string"&&c.includes("@")?void 0:o(c),d=a(r.memberIdOrEmail);return[["organizationId",ee(e,t,r,i,n)],["teamId",o(r.teamId)??(t==="org-team-create"?i:void 0)],["roleId",o(r.roleId)??(t==="org-role-change"?i:void 0)],["roleName",o(r.roleName)??(t==="org-role-change"?o(r.role):void 0)],["role",t==="org-member-role-change"?x(r.role):void 0],["invitationId",o(r.invitationId)??(t==="org-invitation-create"?i:void 0)],["memberId",a(r.memberId)??d],["targetUserId",o(r.userId)]]},re=(e,t)=>{const r=e.body??{},i=e.params??{},n=t==="oauth-token-issue"||t==="oauth-token-revoke"?S(g(e,"authorization")):void 0;return[["clientId",t==="oauth-client-create"?Z(e,t):n??o(r.client_id)??o(i.client_id)??$(r.oauth_query)],["resourceIdentifier",Q(i.identifier??r.identifier)],["consentId",t==="oauth-consent-update"||t==="oauth-consent-revoke"?o(r.id):void 0]]},ie=(e,t)=>{const r=e.body??{},i=e.params??{},n=o(s(e.context?.returned,"id")),a=t.startsWith("admin-")?[["targetUserId",o(r.userId)??q(e,t)]]:t.startsWith("org-")?te(e,t):t.startsWith("oauth-")?re(e,t):t==="token-refresh"?[["clientId",(e.path?.toLowerCase().endsWith("/oauth2/token")===!0?S(g(e,"authorization")):void 0)??o(r.client_id)]]:t.startsWith("scim-")?[["scimUserId",o(i.userId)??(t==="scim-user-create"?n:void 0)],["scimGroupId",o(i.groupId)??(t==="scim-group-create"?n:void 0)]]:t.startsWith("api-key-")?[["keyId",o(t==="api-key-create"?s(e.context?.returned,"id"):r.keyId)]]:t.startsWith("sso-provider-")?[["providerId",o(r.providerId)]]:[],d=t.startsWith("org-team-member-"),c=t.startsWith("admin-")||d?void 0:H(e,t),u=[...a,...c===void 0?[]:[["targetUserId",c]]];return Object.fromEntries(u.flatMap(([m,p])=>p===void 0?[]:[[m,p]]))},oe=(e,{now:t=Date.now(),trustProxyHeaders:r}={})=>{const i=e.body?.grant_type,n=typeof i=="string"?i:void 0,a=e.path===void 0?void 0:b(e.path,e.method,n),d=a===void 0?void 0:V(e,a);if(d===void 0)return;const c=U(e,r),u=g(e,"user-agent"),m=N(e,d);return{...D(e,d),event:d,outcome:d==="oauth-consent"&&e.body?.accept===!1?"failure":h(e),ts:t,...c===void 0?{}:{ip:c},...m===void 0?{}:{targetEmail:m},...u===void 0?{}:{userAgent:u},detail:{path:e.path,...ie(e,d)}}},se=e=>I(async t=>{try{const r=oe(t,{trustProxyHeaders:e.trustProxyHeaders});if(r!==void 0){const i=await C(e.executor,r,{hashKey:t.context.secret,redactDetail:e.redactDetail,retention:e.retention});e.onRecord!==void 0&&await e.onRecord(i)}}catch(r){console.error("@lunora/auth: audit hook failed to record event",r)}}),ne=()=>I(async e=>{try{const{sessionToken:t}=e.body??{};if(b(e.path,e.method)==="admin-session-revoke"&&typeof t=="string"&&t!==""){const r=await e.context.internalAdapter.findSession(t),i=l(r?.session.userId);i!==void 0&&T.set(e.context,i)}}catch(t){console.error("@lunora/auth: audit hook failed to read the revoked session",t)}}),le=(e,t)=>{const r=se(t),i=ne(),n=e.hooks?.after,a=e.hooks?.before,d=a?async u=>(await i(u),a(u)):i,c=n?async u=>{const m=await n(u);return await r(u),m}:r;return{...e,hooks:{...e.hooks,after:c,before:d}}};export{ne as authAuditBeforeHook,se as authAuditHook,oe as buildAuditEntry,b as eventForPath,le as withAuthAudit};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/auth",
3
- "version": "1.0.0-alpha.266",
3
+ "version": "1.0.0-alpha.267",
4
4
  "description": "Auth for Lunora — a thin better-auth wrapper: email/password, OAuth, plugins, D1-backed",
5
5
  "keywords": [
6
6
  "auth",
@@ -1 +0,0 @@
1
- import{decodeBasicCredentials as w}from"@better-auth/core/oauth2";import{cyrb53 as T}from"@lunora/values";import{createAuthMiddleware as _}from"better-auth/api";import{o as S}from"./on-cloudflare-edge-Dx6gFjBO.mjs";import{appendAuthAuditEntry as O}from"../audit.mjs";const A=[["/admin/impersonate-user","admin-impersonate-start"],["/admin/stop-impersonating","admin-impersonate-stop"],["/admin/set-user-password","admin-password-set"],["/admin/set-role","admin-role-change"],["/admin/revoke-user-session","admin-session-revoke"],["/admin/revoke-user-sessions","admin-session-revoke"],["/admin/ban-user","admin-user-ban"],["/admin/unban-user","admin-user-unban"],["/admin/create-user","admin-user-create"],["/admin/update-user","admin-user-update"],["/admin/remove-user","admin-user-remove"],["/api-key/create","api-key-create"],["/api-key/update","api-key-update"],["/api-key/delete","api-key-delete"],["/device/approve","device-approve"],["/device/deny","device-deny"],["/device/token","sign-in"],["/email-otp/change-email","email-change"],["/email-otp/request-email-change","email-change-request"],["/change-email","email-change-request"],["/delete-user","user-delete"],["/delete-user/callback","user-delete"],["/delete-anonymous-user","user-delete"],["/forget-password/email-otp","password-reset-request"],["/email-otp/send-verification-otp","password-reset-request"],["/two-factor/generate-backup-codes","mfa-backup-codes-regenerate"],["/one-time-token/generate","one-time-token-create"],["/one-time-token/verify","sign-in"],["/one-tap/callback","sign-in"],["/passkey/verify-authentication","sign-in"],["/passkey/verify-registration","passkey-add"],["/passkey/delete-passkey","passkey-remove"],["/passkey/update-passkey","passkey-rename"],["/phone-number/verify","sign-in"],["/siwe/verify","sign-in"],["/sso/callback","sign-in"],["/multi-session/set-active","session-switch"],["/multi-session/revoke","session-revoke"],["/oauth2/create-client","oauth-client-create"],["/oauth2/register","oauth-client-create"],["/oauth2/update-client","oauth-client-update"],["/oauth2/delete-client","oauth-client-delete"],["/oauth2/client/rotate-keys","oauth-client-keys-rotate"],["/oauth2/client/rotate-secret","oauth-client-secret-rotate"],["/oauth2/consent","oauth-consent"],["/oauth2/update-consent","oauth-consent-update"],["/oauth2/delete-consent","oauth-consent-revoke"],["/oauth2/revoke","oauth-token-revoke"],["/oauth2/token","oauth-token-issue"],["/oauth2/end-session","sign-out"],["/oauth2/end-session/confirm","sign-out"],["/organization/create","org-create"],["/organization/update","org-update"],["/organization/delete","org-delete"],["/organization/invite-member","org-invitation-create"],["/organization/accept-invitation","org-invitation-accept"],["/organization/reject-invitation","org-invitation-reject"],["/organization/cancel-invitation","org-invitation-cancel"],["/organization/leave","org-member-leave"],["/organization/remove-member","org-member-remove"],["/organization/update-member-role","org-member-role-change"],["/organization/set-active","org-switch"],["/organization/set-active-team","org-team-switch"],["/organization/create-role","org-role-change"],["/organization/update-role","org-role-change"],["/organization/delete-role","org-role-change"],["/organization/create-team","org-team-create"],["/organization/update-team","org-team-update"],["/organization/remove-team","org-team-remove"],["/organization/add-team-member","org-team-member-add"],["/organization/remove-team-member","org-team-member-remove"],["/sso/register","sso-provider-register"],["/sso/update-provider","sso-provider-update"],["/sso/delete-provider","sso-provider-delete"]],I=e=>new RegExp(`${e.split("/").map(t=>t.startsWith(":")?"[^/]+":t.toLowerCase().replaceAll(/[.*+?^${}()|[\]\\]/g,String.raw`\$&`)).join("/")}$`),C=[["POST","/admin/oauth2/resources","oauth-resource-create"],["PATCH","/admin/oauth2/resources/:identifier","oauth-resource-update"],["DELETE","/admin/oauth2/resources/:identifier","oauth-resource-delete"],["POST","/admin/oauth2/resources/:identifier/clients/:client_id","oauth-resource-client-link"],["DELETE","/admin/oauth2/resources/:identifier/clients/:client_id","oauth-resource-client-unlink"],["POST","/scim/v2/Users","scim-user-create"],["PATCH","/scim/v2/Users/:userId","scim-user-update"],["PUT","/scim/v2/Users/:userId","scim-user-update"],["DELETE","/scim/v2/Users/:userId","scim-user-delete"],["POST","/scim/v2/Groups","scim-group-create"],["PATCH","/scim/v2/Groups/:groupId","scim-group-update"],["PUT","/scim/v2/Groups/:groupId","scim-group-update"],["DELETE","/scim/v2/Groups/:groupId","scim-group-delete"]],z=A.map(([e,t])=>({event:t,pattern:I(e)})),P=C.map(([e,t,r])=>({event:r,method:e,pattern:I(t)})),W=e=>{const t=r=>e===r||e.endsWith(r);if(t("/sign-up/email")||t("/sign-up"))return"sign-up";if(t("/sign-in/social")||t("/sign-in/magic-link")||t("/sign-in/sso"))return"sign-in-initiated";if(e.includes("/sign-in/")||e.includes("/callback/")||e.includes("/saml2/sp/acs/")||t("/magic-link/verify")||e.includes("/two-factor/verify-"))return"sign-in";if(t("/sign-out")||e.includes("/saml2/logout/")||e.includes("/saml2/sp/slo/"))return"sign-out";if(t("/change-password")||t("/set-password"))return"password-change";if(t("/reset-password"))return"password-reset";if(t("/request-password-reset")||t("/forget-password"))return"password-reset-request";if(t("/verify-email"))return"email-verification";if(e.includes("/two-factor/enable")||e.includes("/totp/enable"))return"mfa-enable";if(e.includes("/two-factor/disable")||e.includes("/totp/disable"))return"mfa-disable";if(t("/refresh-token")||t("/token"))return"token-refresh";if(t("/revoke-session")||t("/revoke-sessions")||t("/revoke-other-sessions"))return"session-revoke";if(t("/link-social"))return"account-link";if(t("/unlink-account"))return"account-unlink"},L=(e,t,r)=>{const i=e.toLowerCase(),a=t?.toUpperCase(),n=i.includes("/callback/")||i.includes("/saml2/sp/acs/"),d=n?"sign-in":void 0,l=(i.endsWith("/oauth2/token")&&r==="refresh_token"?"token-refresh":void 0)??P.find(u=>u.method===a&&u.pattern.test(i))?.event??(n?void 0:z.find(u=>u.pattern.test(i))?.event)??W(i);return d??l},g=(e,t)=>e.headers?.get(t)??e.request?.headers.get(t)??void 0,U=(e,t)=>{if(S()){const r=g(e,"cf-connecting-ip");if(r!==void 0)return r}if(t===!0)return g(e,"x-forwarded-for")?.split(",")[0]?.trim()},m=e=>typeof e=="string"&&e.length>0?e:void 0,f=256,y=e=>e.length<=f?e:`${e.slice(0,f-15)}~${T(e).toString(16).padStart(14,"0")}`,o=e=>{const t=m(e);if(!(t===void 0||t.includes("@")))return y(t)},s=(e,t)=>typeof e=="object"&&e!==null&&t in e?e[t]:void 0,b=(e,t)=>{const r=e.context?.session,i=e.context?.newSession;return t==="session-revoke"||t==="session-switch"||t==="email-change"?r??i:i??r},D=(e,t)=>{const r=b(e,t),i=m(r?.session?.impersonatedBy);if(i!==void 0)return{actorId:i};const a=r?.user?.id??r?.session?.userId,n=r?.user?.email;return{...a===void 0?{}:{actorId:a},...n===void 0?{}:{actorEmail:n}}},h=e=>{const t=e.context?.returned;if(t instanceof Error)return"failure";if(typeof t=="object"&&t!==null&&"status"in t){const r=Number(t.status);if(Number.isFinite(r)&&r>=400)return"failure"}return"success"},v=320,R=(e,t)=>{if(t!=="sign-in"&&t!=="sign-in-initiated")return;const r=e.body?.email??e.body?.username;if(!(typeof r!="string"||r.length===0))return r.length>v?r.slice(0,v):r},N=(e,t)=>{const r=b(e,t);if(m(r?.session?.impersonatedBy)!==void 0)return m(r?.user?.id)},H=(e,t)=>{if(t==="admin-user-create")return o(s(s(e.context?.returned,"user"),"id"));if(t==="admin-impersonate-stop")return o(s(s(e.context?.session,"user"),"id"))??o(s(s(e.context?.session,"session"),"userId"))},q=e=>{const t=m(e.body?.newEmail)?.toLowerCase();return t!==void 0&&e.context?.newSession?.user?.email===t},F=/\.oauth_logout_confirmation=[^;]/u,G=e=>(e.context?.responseHeaders?.getSetCookie()??[]).some(t=>F.test(t)),M=new Set(["authorization_pending","slow_down"]),j=(e,t,r)=>{let i=t;return t==="email-change-request"&&r.endsWith("/change-email")&&q(e)?i="email-change":t==="sign-out"&&r.endsWith("/oauth2/end-session")&&G(e)?i=void 0:t==="password-reset-request"&&r.endsWith("/email-otp/send-verification-otp")&&(i=e.body?.type==="forget-password"?t:void 0),i},B=(e,t)=>{const r=e.path?.toLowerCase()??"",i=e.context?.returned,a=M.has(m(s(s(i,"body"),"error"))??"");let n;if(t==="sign-in"&&r.endsWith("/phone-number/verify")){const d=m(s(i,"token"))!==void 0;n=e.body?.updatePhoneNumber!==!0&&(d||h(e)==="failure")?"sign-in":"phone-verification"}else t==="user-delete"&&r.endsWith("/delete-user")&&m(s(i,"message"))==="Verification email sent"?n="user-delete-request":t==="sign-in"&&r.endsWith("/device/token")&&a?n=void 0:n=j(e,t,r);return n},$=e=>{if(typeof e=="string")return o(new URLSearchParams(e).get("client_id")??void 0)},V=/^basic /iu,k=(e,t)=>{if(!t.startsWith("org-invitation-"))return;const r=e.context?.returned;return o(s(s(r,"invitation"),"organizationId"))??o(s(s(r,"member"),"organizationId"))??(t==="org-invitation-cancel"?o(s(r,"organizationId")):void 0)},X=(e,t)=>t==="org-switch"?o(s(e.context?.returned,"id")):void 0,K=/^[^?#]*/u,Y=new Set(["did:","urn:"]),J=e=>{const t=m(e);if(t!==void 0)try{const r=new URL(t);r.username="",r.password="",r.search="",r.hash="";const i=r.pathname==="/"?r.href.slice(0,-1):r.href;return r.host===""?Y.has(r.protocol)?o(i):void 0:y(i)}catch{return o(K.exec(t)?.[0])}},E=e=>{if(!(e===void 0||!V.test(e)))try{return o(w(e).clientId)}catch{return}},Q=(e,t)=>t==="oauth-client-create"&&h(e)==="success"?o(s(e.context?.returned,"client_id")):void 0,Z=e=>Array.isArray(e)?o(e.every(t=>typeof t=="string")?e.join(","):void 0):o(e),x=(e,t,r,i,a)=>t==="org-create"?i:t==="org-team-switch"?a:t==="org-team-update"?o(s(r.data,"organizationId"))??a:t.startsWith("org-team-")&&t!=="org-team-create"?o(r.organizationId)??a:t==="org-invitation-accept"||t==="org-invitation-reject"||t==="org-invitation-cancel"?k(e,t):o(r.organizationId)??o(s(e.context?.returned,"organizationId"))??k(e,t)??X(e,t)??a,ee=(e,t)=>{const r=e.body??{},i=o(s(e.context?.returned,"id")),a=t.startsWith("org-member-")||t.startsWith("org-team-")||t==="org-role-change"||t==="org-update"||t==="org-invitation-create"?o(s(s(e.context?.session,"session"),"activeOrganizationId")):void 0,n=c=>typeof c=="string"&&c.includes("@")?void 0:o(c),d=n(r.memberIdOrEmail);return[["organizationId",x(e,t,r,i,a)],["teamId",o(r.teamId)??(t==="org-team-create"?i:void 0)],["roleId",o(r.roleId)??(t==="org-role-change"?i:void 0)],["roleName",o(r.roleName)??(t==="org-role-change"?o(r.role):void 0)],["role",t==="org-member-role-change"?Z(r.role):void 0],["invitationId",o(r.invitationId)??(t==="org-invitation-create"?i:void 0)],["memberId",n(r.memberId)??d],["targetUserId",o(r.userId)]]},te=(e,t)=>{const r=e.body??{},i=e.params??{},a=t==="oauth-token-issue"||t==="oauth-token-revoke"?E(g(e,"authorization")):void 0;return[["clientId",t==="oauth-client-create"?Q(e,t):a??o(r.client_id)??o(i.client_id)??$(r.oauth_query)],["resourceIdentifier",J(i.identifier??r.identifier)],["consentId",t==="oauth-consent-update"||t==="oauth-consent-revoke"?o(r.id):void 0]]},re=(e,t)=>{const r=e.body??{},i=e.params??{},a=o(s(e.context?.returned,"id")),n=t.startsWith("admin-")?[["targetUserId",o(r.userId)??H(e,t)]]:t.startsWith("org-")?ee(e,t):t.startsWith("oauth-")?te(e,t):t==="token-refresh"?[["clientId",(e.path?.toLowerCase().endsWith("/oauth2/token")===!0?E(g(e,"authorization")):void 0)??o(r.client_id)]]:t.startsWith("scim-")?[["scimUserId",o(i.userId)??(t==="scim-user-create"?a:void 0)],["scimGroupId",o(i.groupId)??(t==="scim-group-create"?a:void 0)]]:t.startsWith("api-key-")?[["keyId",o(t==="api-key-create"?s(e.context?.returned,"id"):r.keyId)]]:t.startsWith("sso-provider-")?[["providerId",o(r.providerId)]]:[],d=t.startsWith("org-team-member-"),c=t.startsWith("admin-")||d?void 0:N(e,t),l=[...n,...c===void 0?[]:[["targetUserId",c]]];return Object.fromEntries(l.flatMap(([u,p])=>p===void 0?[]:[[u,p]]))},ie=(e,{now:t=Date.now(),trustProxyHeaders:r}={})=>{const i=e.body?.grant_type,a=typeof i=="string"?i:void 0,n=e.path===void 0?void 0:L(e.path,e.method,a),d=n===void 0?void 0:B(e,n);if(d===void 0)return;const c=U(e,r),l=g(e,"user-agent"),u=R(e,d);return{...D(e,d),event:d,outcome:d==="oauth-consent"&&e.body?.accept===!1?"failure":h(e),ts:t,...c===void 0?{}:{ip:c},...u===void 0?{}:{targetEmail:u},...l===void 0?{}:{userAgent:l},detail:{path:e.path,...re(e,d)}}},oe=e=>_(async t=>{try{const r=ie(t,{trustProxyHeaders:e.trustProxyHeaders});if(r!==void 0){const i=await O(e.executor,r,{hashKey:t.context.secret,redactDetail:e.redactDetail,retention:e.retention});e.onRecord!==void 0&&await e.onRecord(i)}}catch(r){console.error("@lunora/auth: audit hook failed to record event",r)}}),ue=(e,t)=>{const r=oe(t),i=e.hooks?.after,a=i?async n=>{const d=await i(n);return await r(n),d}:r;return{...e,hooks:{...e.hooks,after:a}}};export{oe as authAuditHook,ie as buildAuditEntry,L as eventForPath,ue as withAuthAudit};