@lunora/auth 1.0.0-alpha.117 → 1.0.0-alpha.118
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/README.md +14 -9
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{AUTH_DO_AUDIT_PATH-DiXHh-vn.mjs → AUTH_DO_AUDIT_PATH-CS1FCCoC.mjs} +1 -1
- package/dist/packem_shared/authAuditHook-Bmq06hsp.mjs +1 -0
- package/dist/packem_shared/compileMigrationsSql-CCvK7g57.mjs +1 -0
- package/dist/packem_shared/{createAuth-CtTKaLZN.mjs → createAuth-BI6qU0c_.mjs} +1 -1
- package/dist/packem_shared/{createDoAuthWiring-Ber4dHOy.mjs → createDoAuthWiring-D0pT8Y9R.mjs} +1 -1
- package/package.json +3 -3
- package/dist/packem_shared/authAuditHook-tG8gdR77.mjs +0 -1
- package/dist/packem_shared/compileMigrationsSql-TvwFrqmu.mjs +0 -1
package/README.md
CHANGED
|
@@ -57,20 +57,25 @@ pnpm add @lunora/auth
|
|
|
57
57
|
```ts
|
|
58
58
|
import { createAuth, ensureMigrated, handleAuthRequest, lunoraD1Adapter } from "@lunora/auth";
|
|
59
59
|
|
|
60
|
-
const
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
60
|
+
const options = { secret: env.AUTH_SECRET, emailAndPassword: { enabled: true } };
|
|
61
|
+
|
|
62
|
+
// Prefer lunoraD1Adapter over passing raw env.DB — the raw binding makes
|
|
63
|
+
// better-auth resolve its Kysely adapter via a dynamic import that hangs
|
|
64
|
+
// under @cloudflare/vite-plugin's dev runner.
|
|
65
|
+
const auth = createAuth({ ...options, database: lunoraD1Adapter(env.DB) });
|
|
66
|
+
|
|
67
|
+
// A SECOND instance, over the RAW binding, only for migrating: better-auth
|
|
68
|
+
// migrates through its Kysely adapter alone and throws on lunoraD1Adapter. Build
|
|
69
|
+
// it once and keep it — `ensureMigrated` single-flights on the options object it
|
|
70
|
+
// is handed, so a `createAuth({...})` built inside `fetch` is a fresh key every
|
|
71
|
+
// request and the migration re-runs on each one.
|
|
72
|
+
const migrationAuth = createAuth({ ...options, database: env.DB });
|
|
68
73
|
|
|
69
74
|
// In your Worker's fetch handler, route /api/auth/* to better-auth and fall
|
|
70
75
|
// through to the Lunora worker for everything else:
|
|
71
76
|
export default {
|
|
72
77
|
async fetch(request, env, ctx) {
|
|
73
|
-
await ensureMigrated(
|
|
78
|
+
await ensureMigrated(migrationAuth); // idempotent schema sync; dev/small deploys
|
|
74
79
|
|
|
75
80
|
const authResponse = await handleAuthRequest(auth, request);
|
|
76
81
|
if (authResponse) return authResponse;
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{l as r,a as o,b as a}from"./packem_shared/adapter-DA8DdALX.mjs";import{LunoraAuthAdminError as A,createAuthAdmin as u}from"./packem_shared/LunoraAuthAdminError-BIpCQR2m.mjs";import{AUTH_AUDIT_TABLE as s,appendAuthAuditEntry as m,createAuthAuditReader as l,ensureAuthAuditTable as p,readAuthAuditLog as d}from"./audit.mjs";import{authAuditHook as E,buildAuditEntry as T,eventForPath as f,withAuthAudit as S}from"./packem_shared/authAuditHook-
|
|
1
|
+
import{l as r,a as o,b as a}from"./packem_shared/adapter-DA8DdALX.mjs";import{LunoraAuthAdminError as A,createAuthAdmin as u}from"./packem_shared/LunoraAuthAdminError-BIpCQR2m.mjs";import{AUTH_AUDIT_TABLE as s,appendAuthAuditEntry as m,createAuthAuditReader as l,ensureAuthAuditTable as p,readAuthAuditLog as d}from"./audit.mjs";import{authAuditHook as E,buildAuditEntry as T,eventForPath as f,withAuthAudit as S}from"./packem_shared/authAuditHook-Bmq06hsp.mjs";import{READ_AUDIT_PATH as x,INTERNAL_SECRET_HEADER as D,RESOLVE_SESSION_PATH as H,LunoraAuthDO as U}from"./packem_shared/AUTH_DO_AUDIT_PATH-CS1FCCoC.mjs";import{createAuth as I,resolveAuthOptions as R}from"./packem_shared/createAuth-BI6qU0c_.mjs";import{authDoColumnAdditions as L,authDoSchemaStatements as P}from"./packem_shared/authDoColumnAdditions-BCSs7qaN.mjs";import{createDoAuthWiring as O}from"./packem_shared/createDoAuthWiring-D0pT8Y9R.mjs";import{emailGateDatabaseHooks as N,withEmailGate as w}from"./packem_shared/emailGateDatabaseHooks-CAygR3iq.mjs";import{assertEmailAllowed as M,classifyEmail as k,emailGateMiddleware as q,loadEmailDomainLists as C}from"./email-guard.mjs";import{DEFAULT_AUTH_BASE_PATH as G,handleAuthRequest as B}from"./packem_shared/DEFAULT_AUTH_BASE_PATH-DneiLGpv.mjs";import{createSignUpInvitation as W,listSignUpInvitations as Y,pruneSignUpInvitations as j,revokeSignUpInvitation as z}from"./packem_shared/createSignUpInvitation-CqqQc4S8.mjs";import{LunoraAuthHeadersError as K,withAuthPlugins as Q}from"./middleware.mjs";import{compileMigrationsSql as Z,ensureMigrated as $}from"./packem_shared/compileMigrationsSql-CCvK7g57.mjs";import{default as et}from"./schema.mjs";import{sessionPresets as ot,validateSessionPolicy as at}from"./packem_shared/sessionPresets-C867Mlo4.mjs";import{createSqlAuthStore as At,d1Executor as ut}from"./sql-store.mjs";import{createMemoryAuthStore as st,matchesWhere as mt}from"./store.mjs";import{TURNSTILE_VERIFY_ENDPOINT as pt,verifyTurnstile as dt}from"./turnstile.mjs";import{verifyTurnstileMiddleware as Et}from"./turnstile-middleware.mjs";export{s as AUTH_AUDIT_TABLE,x as AUTH_DO_AUDIT_PATH,D as AUTH_DO_SECRET_HEADER,H as AUTH_DO_SESSION_PATH,G as DEFAULT_AUTH_BASE_PATH,A as LunoraAuthAdminError,U as LunoraAuthDO,K as LunoraAuthHeadersError,pt as TURNSTILE_VERIFY_ENDPOINT,m as appendAuthAuditEntry,M as assertEmailAllowed,E as authAuditHook,L as authDoColumnAdditions,P as authDoSchemaStatements,et as authTables,T as buildAuditEntry,k as classifyEmail,Z as compileMigrationsSql,I as createAuth,u as createAuthAdmin,l as createAuthAuditReader,O as createDoAuthWiring,st as createMemoryAuthStore,W as createSignUpInvitation,At as createSqlAuthStore,ut as d1Executor,N as emailGateDatabaseHooks,q as emailGateMiddleware,p as ensureAuthAuditTable,$ as ensureMigrated,f as eventForPath,B as handleAuthRequest,Y as listSignUpInvitations,C as loadEmailDomainLists,r as lunoraAuthAdapter,o as lunoraD1Adapter,a as lunoraDoAdapter,mt as matchesWhere,j as pruneSignUpInvitations,d as readAuthAuditLog,R as resolveAuthOptions,z as revokeSignUpInvitation,ot as sessionPresets,at as validateSessionPolicy,dt as verifyTurnstile,Et as verifyTurnstileMiddleware,S as withAuthAudit,Q as withAuthPlugins,w as withEmailGate};
|
package/dist/packem_shared/{AUTH_DO_AUDIT_PATH-DiXHh-vn.mjs → AUTH_DO_AUDIT_PATH-CS1FCCoC.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as u,d as h}from"./adapter-DA8DdALX.mjs";import{ensureAuthAuditTable as c,createAuthAuditReader as l}from"../audit.mjs";import{resolveAuthOptions as m,createAuth as d}from"./createAuth-
|
|
1
|
+
import{b as u,d as h}from"./adapter-DA8DdALX.mjs";import{ensureAuthAuditTable as c,createAuthAuditReader as l}from"../audit.mjs";import{resolveAuthOptions as m,createAuth as d}from"./createAuth-BI6qU0c_.mjs";import{authDoSchemaStatements as p,authDoColumnAdditions as f}from"./authDoColumnAdditions-BCSs7qaN.mjs";import{handleAuthRequest as A}from"./DEFAULT_AUTH_BASE_PATH-DneiLGpv.mjs";const g=(n,e)=>{const s=Math.max(n.length,e.length);let t=n.length^e.length;for(let r=0;r<s;r+=1){const i=r<n.length?n.charCodeAt(r):0,o=r<e.length?e.charCodeAt(r):0;t|=i^o}return t===0},R="/__lunora/auth/session",y="/__lunora/auth/audit",S="x-lunora-auth-do-secret",b=n=>{if(n===null||typeof n!="object"||Array.isArray(n))return{error:"body must be a JSON object"};const e={};for(const[s,t]of Object.entries(n))if(s==="limit"||s==="sinceSeq"){if(typeof t!="number"||!Number.isFinite(t))return{error:`"${s}" must be a finite number`};e[s]=t}else if(s==="actorId"||s==="event"){if(typeof t!="string")return{error:`"${s}" must be a string`};e[s]=t}else return{error:`unknown audit read option "${s}"`};return{options:e}};class v{#s;#r;#t;#e;#n=!1;constructor(e,s,t={}){this.#t=e.storage,this.#r=s,this.#s=t}#o(){if(this.#e!==void 0)return this.#e;const e=this.#r();if(!this.#n){const s=m(e);for(const t of p(s))[...this.#t.sql.exec(t)];for(const t of f(s,r=>this.#a(r)))[...this.#t.sql.exec(t)];this.#n=!0}return this.#e=d({...e,database:u(this.#t)}),this.#e}#a(e){return[...this.#t.sql.exec("SELECT name FROM pragma_table_info(?)",e)].map(t=>String(t.name))}async#u(e){if(!this.#i(e))return Response.json({error:"unauthorized"},{status:401});let s;try{s=await e.json()}catch{return Response.json({error:"invalid body"},{status:400})}const t=b(s??{});if("error"in t)return Response.json({error:t.error},{status:400});const r=h(this.#t);await c(r);const i=await l(r).read(t.options);return Response.json({entries:i})}#i(e){const{internalSecret:s}=this.#s;if(s===void 0||s==="")return!1;const t=e.headers.get(S);return t!==null&&g(t,s)}async#h(e){if(!this.#i(e))return Response.json({error:"unauthorized"},{status:401});const t=await this.#o().api.getSession({headers:e.headers}),r=t?.user.id;if(r===void 0)return Response.json({});const i=t?.session.expiresAt,o=t?.user,a=o?.role;return Response.json({...typeof o?.email=="string"&&o.email.length>0?{email:o.email}:{},...i instanceof Date?{expiresAtMs:i.getTime()}:{},...typeof o?.name=="string"&&o.name.length>0?{name:o.name}:{},...typeof a=="string"&&a.length>0?{role:a}:{},userId:r})}async fetch(e){const s=new URL(e.url);if(s.pathname===R)return this.#h(e);if(s.pathname===y)return this.#u(e);const t=this.#o();return await A(t,e,this.#s.basePath)??Response.json({error:"not an auth route"},{status:404})}}export{S as INTERNAL_SECRET_HEADER,v as LunoraAuthDO,y as READ_AUDIT_PATH,R as RESOLVE_SESSION_PATH};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createAuthMiddleware as d}from"better-auth/api";import{appendAuthAuditEntry as c}from"../audit.mjs";import{onCloudflareEdge as l}from"./createAuth-BI6qU0c_.mjs";const f=r=>{const t=r.toLowerCase(),e=i=>t===i||t.endsWith(i);if(e("/sign-up/email")||e("/sign-up"))return"sign-up";if(e("/sign-in/social")||e("/sign-in/magic-link"))return"sign-in-initiated";if(t.includes("/sign-in/")||t.includes("/callback/")||e("/magic-link/verify")||t.includes("/two-factor/verify-"))return"sign-in";if(e("/sign-out"))return"sign-out";if(e("/change-password")||e("/set-password"))return"password-change";if(e("/reset-password")||e("/request-password-reset")||e("/forget-password"))return"password-reset";if(e("/verify-email"))return"email-verification";if(t.includes("/two-factor/enable")||t.includes("/totp/enable"))return"mfa-enable";if(t.includes("/two-factor/disable")||t.includes("/totp/disable"))return"mfa-disable";if(e("/refresh-token")||e("/token"))return"token-refresh";if(e("/revoke-session")||e("/revoke-sessions")||e("/revoke-other-sessions"))return"session-revoke";if(e("/link-social"))return"account-link";if(e("/unlink-account"))return"account-unlink"},a=(r,t)=>r.headers?.get(t)??r.request?.headers.get(t)??void 0,v=(r,t)=>{if(l()){const e=a(r,"cf-connecting-ip");if(e!==void 0)return e}if(t===!0)return a(r,"x-forwarded-for")?.split(",")[0]?.trim()},p=r=>{const t=r.context?.newSession??r.context?.session,e=t?.user?.id??t?.session?.userId,i=t?.user?.email;return{...e===void 0?{}:{actorId:e},...i===void 0?{}:{actorEmail:i}}},h=r=>{const t=r.context?.returned;if(t instanceof Error)return"failure";if(typeof t=="object"&&t!==null&&"status"in t){const e=Number(t.status);if(Number.isFinite(e)&&e>=400)return"failure"}return"success"},u=320,g=(r,t)=>{if(t!=="sign-in"&&t!=="sign-in-initiated")return;const e=r.body?.email??r.body?.username;if(!(typeof e!="string"||e.length===0))return e.length>u?e.slice(0,u):e},m=(r,{now:t=Date.now(),trustProxyHeaders:e}={})=>{const i=r.path===void 0?void 0:f(r.path);if(i===void 0)return;const s=v(r,e),n=a(r,"user-agent"),o=g(r,i);return{...p(r),event:i,outcome:h(r),ts:t,...s===void 0?{}:{ip:s},...o===void 0?{}:{targetEmail:o},...n===void 0?{}:{userAgent:n},detail:{path:r.path}}},w=r=>d(async t=>{try{const e=m(t,{trustProxyHeaders:r.trustProxyHeaders});if(e!==void 0){const i=await c(r.executor,e,{redactDetail:r.redactDetail,retention:r.retention});r.onRecord!==void 0&&await r.onRecord(i)}}catch(e){console.error("@lunora/auth: audit hook failed to record event",e)}}),A=(r,t)=>{const e=w(t),i=r.hooks?.after,s=i?async n=>{const o=await i(n);return await e(n),o}:e;return{...r,hooks:{...r.hooks,after:s}}};export{w as authAuditHook,m as buildAuditEntry,f as eventForPath,A as withAuthAudit};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as g}from"@lunora/errors";import{getMigrations as u}from"better-auth/db/migration";import{resolveAuthOptions as w}from"./createAuth-BI6qU0c_.mjs";const I=/pragma_index_list\s*\(/iu,_=/sqlite_master/iu,y=/^["`[]|["\]`]$/gu,R=/\s+/u,x=/create\s+unique\s+index/iu,M=/\bwhere\b/iu,T=t=>I.test(t)&&_.test(t),D=t=>(t.trim().split(R)[0]??"").replaceAll(y,"").trim(),A=t=>{const n=t.indexOf("(");if(n===-1)return{columns:[],tail:""};let s=0;for(let e=n;e<t.length;e+=1){const o=t[e];if(o==="(")s+=1;else if(o===")"&&(s-=1,s===0))return{columns:t.slice(n+1,e).split(",").map(i=>D(i)).filter(i=>i!==""),tail:t.slice(e+1)}}return{columns:[],tail:""}},P=async t=>{const n=t.prepare("SELECT name, tbl_name, sql FROM sqlite_master WHERE type = 'index'"),{results:s}=await n.all(),e=[];for(const o of s??[]){const i=o.name,a=o.tbl_name,r=o.sql;if(typeof i!="string"||typeof a!="string")continue;if(typeof r!="string"){e.push({columnPosition:0,indexName:i,isPartial:0,isUnique:1,tableName:a});continue}const m=x.test(r)?1:0,{columns:f,tail:d}=A(r),h=M.test(d)?1:0;for(const[E,b]of f.entries())e.push({columnName:b,columnPosition:E,indexName:i,isPartial:h,isUnique:m,tableName:a})}return e},N=t=>{const n=async()=>{const e=await P(t);return{meta:{},results:e,success:!0}},s={all:n,bind:()=>s,run:n};return s},U=t=>new Proxy(t,{get(n,s,e){if(s==="prepare")return i=>T(i)?N(n):n.prepare(i);const o=Reflect.get(n,s,e);return typeof o=="function"?o.bind(n):o}}),O=t=>typeof t=="object"&&t!==null&&typeof t.prepare=="function"&&typeof t.batch=="function",l=t=>{const{database:n}=t;if(!(n&&typeof n!="function"))throw new g("AUTH_MIGRATOR_UNSUPPORTED",n?"@lunora/auth: this auth instance's `database` is a custom adapter, which better-auth's migrator cannot drive.":"@lunora/auth: this auth instance has no `database`, so better-auth's migrator has nothing to introspect.")},p=t=>O(t.database)?{...t,database:U(t.database)}:t,c=new WeakMap,H=async t=>{const{options:n}=t;l(n);const s=c.get(n);if(s){await s;return}const e=(async()=>{const{runMigrations:o}=await u(p(n));await o()})();c.set(n,e);try{await e}catch(o){throw c.delete(n),o}},L=async t=>{const n=w(t);l(n);const{compileMigrations:s}=await u(p(n));return s()};export{L as compileMigrationsSql,H as ensureMigrated};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as c}from"@lunora/errors";import{betterAuth as l}from"better-auth";import{getIP as u}from"better-auth/api";import{validateSessionPolicy as f}from"./sessionPresets-C867Mlo4.mjs";const n="cf-connecting-ip",h=()=>globalThis.navigator?.userAgent==="Cloudflare-Workers",m=e=>{const t=e!==void 0&&e.length>0;return h()?t?[n,"x-forwarded-for"]:[n]:t?["x-forwarded-for"]:[]},a="/**",p=100,A=e=>{const t=e.rateLimit?.customRules??{};return t[a]!==void 0?t:{...t,[a]:(o,r)=>u(o,e)===null?{max:r.max*p,window:r.window}:r}},d=32,E=e=>{const t=typeof e=="string"?e.trim().length:0;return t>0&&t<d},i=e=>typeof e=="string"?e.toLowerCase().startsWith("http://"):e&&typeof e=="object"?e.protocol==="http"?!0:e.protocol==="https"?!1:typeof e.fallback=="string"&&e.fallback.toLowerCase().startsWith("http://"):!1,g=new Set(["127.0.0.1","localhost"]),L=e=>{if(typeof e!="string")return;let t;try{t=new URL(e)}catch{return}if(!(t.protocol!=="http:"||!g.has(t.hostname)))return{allowedHosts:[t.hostname,`${t.hostname}:*`],fallback:e,protocol:"http"}},C=e=>{const t=L(e.baseURL)??e.baseURL;if(E(e.secret)){const s=`@lunora/auth: AUTH_SECRET is only ${String(e.secret?.trim().length)} characters. Use at least ${String(d)} for a brute-force-resistant secret — generate one with \`openssl rand -hex 32\`.`;if(!i(t))throw new c("INTERNAL",s);console.warn(s)}const o=e.advanced??{},r=o.ipAddress??{};return{...e,advanced:{...o,defaultCookieAttributes:o.defaultCookieAttributes??{httpOnly:!0,path:"/",sameSite:"lax"},ipAddress:{...r,...r.ipAddressHeaders===void 0?{ipAddressHeaders:m(r.trustedProxies)}:{}},...o.useSecureCookies===void 0?{useSecureCookies:!i(t)}:{}},baseURL:t}},v=e=>{const t=C(e),o=t.rateLimit?.enabled===void 0,r=t.rateLimit?.storage===void 0&&t.rateLimit?.enabled!==!1,s=t.rateLimit?.enabled===!1?{}:{rateLimit:{...t.rateLimit,...o?{enabled:!0}:{},...r?{storage:"database"}:{},customRules:A(t)}};return{...t,...s,...t.session?.cookieCache===void 0?{session:{...t.session,cookieCache:{enabled:!0,maxAge:60}}}:{}}},H=e=>{if(!e.secret||e.secret.trim()==="")throw new c("INTERNAL",'@lunora/auth: `secret` is required. Set AUTH_SECRET locally in .dev.vars (`lunora env set AUTH_SECRET "$(openssl rand -hex 32)"`), and in production with `wrangler secret put AUTH_SECRET`.');return e.session&&f(e.session),l(v(e))};export{H as createAuth,v as resolveAuthOptions};
|
|
1
|
+
import{LunoraError as c}from"@lunora/errors";import{betterAuth as l}from"better-auth";import{getIP as u}from"better-auth/api";import{validateSessionPolicy as f}from"./sessionPresets-C867Mlo4.mjs";const n="cf-connecting-ip",h=()=>globalThis.navigator?.userAgent==="Cloudflare-Workers",m=e=>{const t=e!==void 0&&e.length>0;return h()?t?[n,"x-forwarded-for"]:[n]:t?["x-forwarded-for"]:[]},a="/**",p=100,A=e=>{const t=e.rateLimit?.customRules??{};return t[a]!==void 0?t:{...t,[a]:(o,r)=>u(o,e)===null?{max:r.max*p,window:r.window}:r}},d=32,E=e=>{const t=typeof e=="string"?e.trim().length:0;return t>0&&t<d},i=e=>typeof e=="string"?e.toLowerCase().startsWith("http://"):e&&typeof e=="object"?e.protocol==="http"?!0:e.protocol==="https"?!1:typeof e.fallback=="string"&&e.fallback.toLowerCase().startsWith("http://"):!1,g=new Set(["127.0.0.1","localhost"]),L=e=>{if(typeof e!="string")return;let t;try{t=new URL(e)}catch{return}if(!(t.protocol!=="http:"||!g.has(t.hostname)))return{allowedHosts:[t.hostname,`${t.hostname}:*`],fallback:e,protocol:"http"}},C=e=>{const t=L(e.baseURL)??e.baseURL;if(E(e.secret)){const s=`@lunora/auth: AUTH_SECRET is only ${String(e.secret?.trim().length)} characters. Use at least ${String(d)} for a brute-force-resistant secret — generate one with \`openssl rand -hex 32\`.`;if(!i(t))throw new c("INTERNAL",s);console.warn(s)}const o=e.advanced??{},r=o.ipAddress??{};return{...e,advanced:{...o,defaultCookieAttributes:o.defaultCookieAttributes??{httpOnly:!0,path:"/",sameSite:"lax"},ipAddress:{...r,...r.ipAddressHeaders===void 0?{ipAddressHeaders:m(r.trustedProxies)}:{}},...o.useSecureCookies===void 0?{useSecureCookies:!i(t)}:{}},baseURL:t}},v=e=>{const t=C(e),o=t.rateLimit?.enabled===void 0,r=t.rateLimit?.storage===void 0&&t.rateLimit?.enabled!==!1,s=t.rateLimit?.enabled===!1?{}:{rateLimit:{...t.rateLimit,...o?{enabled:!0}:{},...r?{storage:"database"}:{},customRules:A(t)}};return{...t,...s,...t.session?.cookieCache===void 0?{session:{...t.session,cookieCache:{enabled:!0,maxAge:60}}}:{}}},H=e=>{if(!e.secret||e.secret.trim()==="")throw new c("INTERNAL",'@lunora/auth: `secret` is required. Set AUTH_SECRET locally in .dev.vars (`lunora env set AUTH_SECRET "$(openssl rand -hex 32)"`), and in production with `wrangler secret put AUTH_SECRET`.');return e.session&&f(e.session),l(v(e))};export{H as createAuth,h as onCloudflareEdge,v as resolveAuthOptions};
|
package/dist/packem_shared/{createDoAuthWiring-Ber4dHOy.mjs → createDoAuthWiring-D0pT8Y9R.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{INTERNAL_SECRET_HEADER as u,RESOLVE_SESSION_PATH as p,READ_AUDIT_PATH as f}from"./AUTH_DO_AUDIT_PATH-
|
|
1
|
+
import{INTERNAL_SECRET_HEADER as u,RESOLVE_SESSION_PATH as p,READ_AUDIT_PATH as f}from"./AUTH_DO_AUDIT_PATH-CS1FCCoC.mjs";import{DEFAULT_AUTH_BASE_PATH as h,isAuthRoutePath as A}from"./DEFAULT_AUTH_BASE_PATH-DneiLGpv.mjs";const g=l=>{const{basePath:c=h,internalSecret:a,namespace:o,objectName:d="auth"}=l,i=()=>{if(o)return o.get(o.idFromName(d))},m=async(t,n,r)=>{if(!a)return;const s=i();if(!s)return;const e=await s.fetch(new Request(new URL(t,n),{body:JSON.stringify(r),headers:{"content-type":"application/json",[u]:a},method:"POST"}));return e.ok?e:void 0};return{auditReader:{read:async t=>{const n=await m(f,"https://auth-do.invalid",t);return n?(await n.json())?.entries??[]:[]}},authHandler:async t=>{if(A(new URL(t.url).pathname,c))return i()?.fetch(t)},resolveIdentity:async t=>{if(!a)return null;const n=i();if(!n)return null;const r=new Headers(t.headers);r.set(u,a);const s=await n.fetch(new Request(new URL(p,t.url),{headers:r}));if(!s.ok)return null;const e=await s.json();return e?.userId?{...typeof e.email=="string"&&e.email.length>0?{email:e.email}:{},...typeof e.expiresAtMs=="number"&&Number.isFinite(e.expiresAtMs)?{expiresAtMs:e.expiresAtMs}:{},...typeof e.name=="string"&&e.name.length>0?{name:e.name}:{},...typeof e.role=="string"&&e.role.length>0?{role:e.role}:{},userId:e.userId}:null}}};export{g as createDoAuthWiring};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/auth",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.118",
|
|
4
4
|
"description": "Auth for Lunora — a thin better-auth wrapper: email/password, OAuth, plugins, D1-backed",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"auth",
|
|
@@ -103,8 +103,8 @@
|
|
|
103
103
|
"@better-auth/oauth-provider": "1.7.1",
|
|
104
104
|
"@better-auth/passkey": "1.7.1",
|
|
105
105
|
"@better-auth/scim": "1.7.1",
|
|
106
|
-
"@lunora/errors": "1.0.0-alpha.
|
|
107
|
-
"@lunora/values": "1.0.0-alpha.
|
|
106
|
+
"@lunora/errors": "1.0.0-alpha.32",
|
|
107
|
+
"@lunora/values": "1.0.0-alpha.40",
|
|
108
108
|
"@visulima/disposable-email-domains": "1.1.0",
|
|
109
109
|
"@visulima/email-verifier": "1.0.2",
|
|
110
110
|
"@visulima/free-email-domains": "1.0.1",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{createAuthMiddleware as d}from"better-auth/api";import{appendAuthAuditEntry as c}from"../audit.mjs";const l=r=>{const t=r.toLowerCase(),e=i=>t===i||t.endsWith(i);if(e("/sign-up/email")||e("/sign-up"))return"sign-up";if(e("/sign-in/social")||e("/sign-in/magic-link"))return"sign-in-initiated";if(t.includes("/sign-in/")||t.includes("/callback/")||e("/magic-link/verify")||t.includes("/two-factor/verify-"))return"sign-in";if(e("/sign-out"))return"sign-out";if(e("/change-password")||e("/set-password"))return"password-change";if(e("/reset-password")||e("/request-password-reset")||e("/forget-password"))return"password-reset";if(e("/verify-email"))return"email-verification";if(t.includes("/two-factor/enable")||t.includes("/totp/enable"))return"mfa-enable";if(t.includes("/two-factor/disable")||t.includes("/totp/disable"))return"mfa-disable";if(e("/refresh-token")||e("/token"))return"token-refresh";if(e("/revoke-session")||e("/revoke-sessions")||e("/revoke-other-sessions"))return"session-revoke";if(e("/link-social"))return"account-link";if(e("/unlink-account"))return"account-unlink"},a=(r,t)=>r.headers?.get(t)??r.request?.headers.get(t)??void 0,f=(r,t)=>{const e=a(r,"cf-connecting-ip");if(e!==void 0)return e;if(t===!0)return a(r,"x-forwarded-for")?.split(",")[0]?.trim()},v=r=>{const t=r.context?.newSession??r.context?.session,e=t?.user?.id??t?.session?.userId,i=t?.user?.email;return{...e===void 0?{}:{actorId:e},...i===void 0?{}:{actorEmail:i}}},h=r=>{const t=r.context?.returned;if(t instanceof Error)return"failure";if(typeof t=="object"&&t!==null&&"status"in t){const e=Number(t.status);if(Number.isFinite(e)&&e>=400)return"failure"}return"success"},u=320,p=(r,t)=>{if(t!=="sign-in"&&t!=="sign-in-initiated")return;const e=r.body?.email??r.body?.username;if(!(typeof e!="string"||e.length===0))return e.length>u?e.slice(0,u):e},g=(r,{now:t=Date.now(),trustProxyHeaders:e}={})=>{const i=r.path===void 0?void 0:l(r.path);if(i===void 0)return;const s=f(r,e),n=a(r,"user-agent"),o=p(r,i);return{...v(r),event:i,outcome:h(r),ts:t,...s===void 0?{}:{ip:s},...o===void 0?{}:{targetEmail:o},...n===void 0?{}:{userAgent:n},detail:{path:r.path}}},m=r=>d(async t=>{try{const e=g(t,{trustProxyHeaders:r.trustProxyHeaders});if(e!==void 0){const i=await c(r.executor,e,{redactDetail:r.redactDetail,retention:r.retention});r.onRecord!==void 0&&await r.onRecord(i)}}catch(e){console.error("@lunora/auth: audit hook failed to record event",e)}}),y=(r,t)=>{const e=m(t),i=r.hooks?.after,s=i?async n=>{const o=await i(n);return await e(n),o}:e;return{...r,hooks:{...r.hooks,after:s}}};export{m as authAuditHook,g as buildAuditEntry,l as eventForPath,y as withAuthAudit};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{getMigrations as l}from"better-auth/db/migration";import{resolveAuthOptions as I}from"./createAuth-CtTKaLZN.mjs";const w=/pragma_index_list\s*\(/iu,b=/sqlite_master/iu,h=/^["`[]|["\]`]$/gu,y=/\s+/u,_=/create\s+unique\s+index/iu,x=/\bwhere\b/iu,M=t=>w.test(t)&&b.test(t),R=t=>(t.trim().split(y)[0]??"").replaceAll(h,"").trim(),D=t=>{const n=t.indexOf("(");if(n===-1)return{columns:[],tail:""};let s=0;for(let e=n;e<t.length;e+=1){const o=t[e];if(o==="(")s+=1;else if(o===")"&&(s-=1,s===0))return{columns:t.slice(n+1,e).split(",").map(i=>R(i)).filter(i=>i!==""),tail:t.slice(e+1)}}return{columns:[],tail:""}},T=async t=>{const n=t.prepare("SELECT name, tbl_name, sql FROM sqlite_master WHERE type = 'index'"),{results:s}=await n.all(),e=[];for(const o of s??[]){const i=o.name,r=o.tbl_name,a=o.sql;if(typeof i!="string"||typeof r!="string")continue;if(typeof a!="string"){e.push({columnPosition:0,indexName:i,isPartial:0,isUnique:1,tableName:r});continue}const p=_.test(a)?1:0,{columns:m,tail:f}=D(a),d=x.test(f)?1:0;for(const[E,g]of m.entries())e.push({columnName:g,columnPosition:E,indexName:i,isPartial:d,isUnique:p,tableName:r})}return e},A=t=>{const n=async()=>{const e=await T(t);return{meta:{},results:e,success:!0}},s={all:n,bind:()=>s,run:n};return s},N=t=>new Proxy(t,{get(n,s,e){if(s==="prepare")return i=>M(i)?A(n):n.prepare(i);const o=Reflect.get(n,s,e);return typeof o=="function"?o.bind(n):o}}),P=t=>typeof t=="object"&&t!==null&&typeof t.prepare=="function"&&typeof t.batch=="function",u=t=>P(t.database)?{...t,database:N(t.database)}:t,c=new WeakMap,S=async t=>{const{options:n}=t,s=c.get(n);if(s){await s;return}const e=(async()=>{const{runMigrations:o}=await l(u(n));await o()})();c.set(n,e);try{await e}catch(o){throw c.delete(n),o}},U=async t=>{const{compileMigrations:n}=await l(u(I(t)));return n()};export{U as compileMigrationsSql,S as ensureMigrated};
|