@lunora/auth 1.0.0-alpha.70 → 1.0.0-alpha.72
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/audit.mjs +2 -2
- package/dist/index.mjs +1 -1
- package/dist/middleware.d.mts +4 -4
- package/dist/middleware.d.ts +4 -4
- package/dist/packem_shared/LunoraAuthAdminError-CMUphsi_.mjs +1 -0
- package/dist/packem_shared/createLunoraAuthClient-gxLo2pKj.mjs +1 -0
- package/dist/plugins-client.mjs +1 -1
- package/package.json +4 -4
- package/dist/packem_shared/LunoraAuthAdminError-CiHsF1qZ.mjs +0 -1
- package/dist/packem_shared/createLunoraAuthClient-CedinxXU.mjs +0 -1
package/dist/audit.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{redact as
|
|
1
|
+
import{redact as p,standardRules as A,piiRules as g}from"@visulima/redact";const n="__lunora_auth_audit__",L=[...A,...g],N=1e3,R=1e4,o=null,E=t=>{if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="bigint"||typeof t=="boolean")return String(t)},d=async t=>{await t.run(`CREATE TABLE IF NOT EXISTS "${n}" (
|
|
2
2
|
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
3
3
|
ts REAL NOT NULL,
|
|
4
4
|
event TEXT NOT NULL,
|
|
@@ -9,4 +9,4 @@ import{redact as A,standardRules as g,piiRules as L}from"@visulima/redact";const
|
|
|
9
9
|
ip TEXT,
|
|
10
10
|
user_agent TEXT,
|
|
11
11
|
detail TEXT
|
|
12
|
-
)`,[]);try{await t.run(`ALTER TABLE "${
|
|
12
|
+
)`,[]);try{await t.run(`ALTER TABLE "${n}" ADD COLUMN target_email TEXT`,[])}catch(e){if(!(e instanceof Error?e.message.toLowerCase():String(e).toLowerCase()).includes("duplicate column"))throw e}},I=async(t,e,i={})=>{await d(t);let a;return e.detail!==void 0&&(a=i.redactDetail===!1?e.detail:p(e.detail,L)),await t.run(`INSERT INTO "${n}" (ts, event, outcome, actor_id, actor_email, target_email, ip, user_agent, detail) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[e.ts,e.event,e.outcome,e.actorId??o,e.actorEmail??o,e.targetEmail??o,e.ip??o,e.userAgent??o,a===void 0?o:JSON.stringify(a)]),typeof i.retention=="number"&&i.retention>0&&await t.run(`DELETE FROM "${n}" WHERE seq <= (SELECT MAX(seq) - ? FROM "${n}")`,[i.retention]),{...e,detail:a}},f=async(t,e={})=>{await d(t);const i=Number.isFinite(e.limit)?Math.max(1,Math.min(e.limit,R)):N,a=["seq > ?"],s=[e.sinceSeq??0];return e.actorId!==void 0&&(a.push("actor_id = ?"),s.push(e.actorId)),e.event!==void 0&&(a.push("event = ?"),s.push(e.event)),s.push(i),(await t.all(`SELECT seq, ts, event, outcome, actor_id, actor_email, target_email, ip, user_agent, detail FROM "${n}" WHERE ${a.join(" AND ")} ORDER BY seq DESC LIMIT ?`,s)).map(r=>{const u={event:E(r.event)??"",outcome:r.outcome==="failure"?"failure":"success",seq:Number(r.seq),ts:Number(r.ts)},T=[["actorId","actor_id"],["actorEmail","actor_email"],["targetEmail","target_email"],["ip","ip"],["userAgent","user_agent"]];for(const[m,_]of T){const l=E(r[_]);l!==void 0&&(u[m]=l)}const c=E(r.detail);return c!==void 0&&(u.detail=JSON.parse(c)),u})},h=t=>({read:e=>f(t,e)});export{n as AUTH_AUDIT_TABLE,I as appendAuthAuditEntry,h as createAuthAuditReader,d as ensureAuthAuditTable,f as readAuthAuditLog};
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{s as r,l as o,w as a}from"./packem_shared/adapter-RvDcm0Zy.mjs";import{LunoraAuthAdminError as u,createAuthAdmin as i}from"./packem_shared/LunoraAuthAdminError-
|
|
1
|
+
import{s as r,l as o,w as a}from"./packem_shared/adapter-RvDcm0Zy.mjs";import{LunoraAuthAdminError as u,createAuthAdmin as i}from"./packem_shared/LunoraAuthAdminError-CMUphsi_.mjs";import{AUTH_AUDIT_TABLE as m,appendAuthAuditEntry as l,createAuthAuditReader as d,ensureAuthAuditTable as h,readAuthAuditLog as E}from"./audit.mjs";import{authAuditHook as p,buildAuditEntry as T,eventForPath as f,withAuthAudit as _}from"./packem_shared/authAuditHook-DG_ZNO53.mjs";import{READ_AUDIT_PATH as D,INTERNAL_SECRET_HEADER as S,RESOLVE_SESSION_PATH as H,LunoraAuthDO as c}from"./packem_shared/AUTH_DO_AUDIT_PATH-C4897amZ.mjs";import{createAuth as L,resolveAuthOptions as P}from"./packem_shared/createAuth-DRtd4q6u.mjs";import{authDoColumnAdditions as I,authDoSchemaStatements as O}from"./packem_shared/authDoColumnAdditions-B8BRbdzn.mjs";import{createDoAuthWiring as y}from"./packem_shared/createDoAuthWiring-acnXUGZr.mjs";import{emailGateDatabaseHooks as g,withEmailGate as v}from"./packem_shared/emailGateDatabaseHooks-DzBD1Qoq.mjs";import{assertEmailAllowed as b,classifyEmail as q,emailGateMiddleware as C,loadEmailDomainLists as F}from"./email-guard.mjs";import{DEFAULT_AUTH_BASE_PATH as k,handleAuthRequest as B}from"./packem_shared/DEFAULT_AUTH_BASE_PATH-kIwlEt8i.mjs";import{LunoraAuthHeadersError as W,withAuthPlugins as Y}from"./middleware.mjs";import{compileMigrationsSql as z,ensureMigrated as J}from"./packem_shared/compileMigrationsSql-BcvcHAqo.mjs";import{default as Q}from"./schema.mjs";import{sessionPresets as Z,validateSessionPolicy as $}from"./packem_shared/sessionPresets-DpEFjXKV.mjs";import{createSqlAuthStore as te,d1Executor as re}from"./sql-store.mjs";import{createMemoryAuthStore as ae,matchesWhere as Ae}from"./store.mjs";import{TURNSTILE_VERIFY_ENDPOINT as ie,verifyTurnstile as se}from"./turnstile.mjs";import{verifyTurnstileMiddleware as le}from"./turnstile-middleware.mjs";export{m as AUTH_AUDIT_TABLE,D as AUTH_DO_AUDIT_PATH,S as AUTH_DO_SECRET_HEADER,H as AUTH_DO_SESSION_PATH,k as DEFAULT_AUTH_BASE_PATH,u as LunoraAuthAdminError,c as LunoraAuthDO,W as LunoraAuthHeadersError,ie as TURNSTILE_VERIFY_ENDPOINT,l as appendAuthAuditEntry,b as assertEmailAllowed,p as authAuditHook,I as authDoColumnAdditions,O as authDoSchemaStatements,Q as authTables,T as buildAuditEntry,q as classifyEmail,z as compileMigrationsSql,L as createAuth,i as createAuthAdmin,d as createAuthAuditReader,y as createDoAuthWiring,ae as createMemoryAuthStore,te as createSqlAuthStore,re as d1Executor,g as emailGateDatabaseHooks,C as emailGateMiddleware,h as ensureAuthAuditTable,J as ensureMigrated,f as eventForPath,B as handleAuthRequest,F as loadEmailDomainLists,r as lunoraAuthAdapter,o as lunoraD1Adapter,a as lunoraDoAdapter,Ae as matchesWhere,E as readAuthAuditLog,P as resolveAuthOptions,Z as sessionPresets,$ as validateSessionPolicy,se as verifyTurnstile,le as verifyTurnstileMiddleware,_ as withAuthAudit,Y as withAuthPlugins,v as withEmailGate};
|
package/dist/middleware.d.mts
CHANGED
|
@@ -24,7 +24,7 @@ interface MiddlewareNext<ContextIn> {
|
|
|
24
24
|
* authorization bypass, so a call that trips the lint also trips this guard.
|
|
25
25
|
*/
|
|
26
26
|
declare class LunoraAuthHeadersError extends LunoraError {
|
|
27
|
-
/** The `ctx.authApi
|
|
27
|
+
/** The `ctx.authApi.<method>` that was called without `headers`. */
|
|
28
28
|
readonly method: string;
|
|
29
29
|
constructor(method: string);
|
|
30
30
|
}
|
|
@@ -36,7 +36,7 @@ interface WithAuthPluginsOptions {
|
|
|
36
36
|
* Whether to install the runtime header guard around `ctx.authApi`.
|
|
37
37
|
*
|
|
38
38
|
* **Defaults to `true` — the safe default.** When enabled, every
|
|
39
|
-
* `ctx.authApi
|
|
39
|
+
* `ctx.authApi.<method>(…)` call that omits `headers` throws
|
|
40
40
|
* {@link LunoraAuthHeadersError} instead of silently running with full
|
|
41
41
|
* server-to-server privileges. For a deliberate, per-call unauthenticated
|
|
42
42
|
* invocation, use the explicit `ctx.authApi.withoutHeaders()` escape hatch
|
|
@@ -89,7 +89,7 @@ interface LunoraAuthApiContext<Auth extends LunoraAuth> {
|
|
|
89
89
|
* statically; the guard is the runtime backstop for the cases the lint
|
|
90
90
|
* can't see (dynamic method names, indirected calls). For the rare,
|
|
91
91
|
* deliberate unauthenticated server-to-server call, opt out explicitly with
|
|
92
|
-
* `ctx.authApi.withoutHeaders()
|
|
92
|
+
* `ctx.authApi.withoutHeaders().<method>(…)`.
|
|
93
93
|
*
|
|
94
94
|
* Lunora's procedure context carries only the resolved identity, not the
|
|
95
95
|
* raw inbound `Headers`, so this middleware CANNOT pre-bind them for you.
|
|
@@ -179,7 +179,7 @@ interface LunoraAuthApiContext<Auth extends LunoraAuth> {
|
|
|
179
179
|
* Shape of the middleware {@link withAuthPlugins} returns: a callable generic
|
|
180
180
|
* over the incoming ctx so chaining `.use(...)` preserves whatever ctx fields
|
|
181
181
|
* the upstream middleware already installed. Lives as its own interface
|
|
182
|
-
* because TypeScript doesn't allow declaring `const fn:
|
|
182
|
+
* because TypeScript doesn't allow declaring `const fn: <CtxIn>() => ...` —
|
|
183
183
|
* the generic must live on a callable type alias or interface.
|
|
184
184
|
*/
|
|
185
185
|
type WithAuthPluginsMiddleware<Auth extends LunoraAuth> = <ContextIn>(options: {
|
package/dist/middleware.d.ts
CHANGED
|
@@ -24,7 +24,7 @@ interface MiddlewareNext<ContextIn> {
|
|
|
24
24
|
* authorization bypass, so a call that trips the lint also trips this guard.
|
|
25
25
|
*/
|
|
26
26
|
declare class LunoraAuthHeadersError extends LunoraError {
|
|
27
|
-
/** The `ctx.authApi
|
|
27
|
+
/** The `ctx.authApi.<method>` that was called without `headers`. */
|
|
28
28
|
readonly method: string;
|
|
29
29
|
constructor(method: string);
|
|
30
30
|
}
|
|
@@ -36,7 +36,7 @@ interface WithAuthPluginsOptions {
|
|
|
36
36
|
* Whether to install the runtime header guard around `ctx.authApi`.
|
|
37
37
|
*
|
|
38
38
|
* **Defaults to `true` — the safe default.** When enabled, every
|
|
39
|
-
* `ctx.authApi
|
|
39
|
+
* `ctx.authApi.<method>(…)` call that omits `headers` throws
|
|
40
40
|
* {@link LunoraAuthHeadersError} instead of silently running with full
|
|
41
41
|
* server-to-server privileges. For a deliberate, per-call unauthenticated
|
|
42
42
|
* invocation, use the explicit `ctx.authApi.withoutHeaders()` escape hatch
|
|
@@ -89,7 +89,7 @@ interface LunoraAuthApiContext<Auth extends LunoraAuth> {
|
|
|
89
89
|
* statically; the guard is the runtime backstop for the cases the lint
|
|
90
90
|
* can't see (dynamic method names, indirected calls). For the rare,
|
|
91
91
|
* deliberate unauthenticated server-to-server call, opt out explicitly with
|
|
92
|
-
* `ctx.authApi.withoutHeaders()
|
|
92
|
+
* `ctx.authApi.withoutHeaders().<method>(…)`.
|
|
93
93
|
*
|
|
94
94
|
* Lunora's procedure context carries only the resolved identity, not the
|
|
95
95
|
* raw inbound `Headers`, so this middleware CANNOT pre-bind them for you.
|
|
@@ -179,7 +179,7 @@ interface LunoraAuthApiContext<Auth extends LunoraAuth> {
|
|
|
179
179
|
* Shape of the middleware {@link withAuthPlugins} returns: a callable generic
|
|
180
180
|
* over the incoming ctx so chaining `.use(...)` preserves whatever ctx fields
|
|
181
181
|
* the upstream middleware already installed. Lives as its own interface
|
|
182
|
-
* because TypeScript doesn't allow declaring `const fn:
|
|
182
|
+
* because TypeScript doesn't allow declaring `const fn: <CtxIn>() => ...` —
|
|
183
183
|
* the generic must live on a callable type alias or interface.
|
|
184
184
|
*/
|
|
185
185
|
type WithAuthPluginsMiddleware<Auth extends LunoraAuth> = <ContextIn>(options: {
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createLocalAccountIssuer as S}from"@better-auth/core/db";import{LunoraError as O}from"@lunora/errors";import{getAuthTables as A}from"better-auth/db";class p extends O{constructor(c,w){super(w,c,{name:"LunoraAuthAdminError"})}}const M=50,D=500,z=3600,R=z*24,U=100*365*24*60*60,N=2880*60*1e3,k=new Set(["accessToken","backupCodes","idToken","password","publicKey","refreshToken","secret","token"]),T=s=>Math.min(Math.max(Math.trunc(s??M),1),D),x=s=>Math.max(0,Math.trunc(s??0)),u=s=>{const c={};for(const[w,m]of Object.entries(s))k.has(w)||(c[w]=m instanceof Date?m.getTime():m);return c},I=s=>Array.isArray(s)?s.join(","):s,b=s=>s.toLowerCase().replaceAll(/[^\da-z]+/g,"-").replaceAll(/^-|-$/g,""),E=new Set(["banExpires","banned","banReason","createdAt","email","emailVerified","id","name","role","updatedAt"]),L={displayUsername:"username",phoneNumber:"phone-number",phoneNumberVerified:"phone-number",username:"username"},_=s=>s==="boolean"||s==="date"||s==="number"?s:"string",P=s=>{const c=[];for(const[w,m]of Object.entries(s))m.input===!1||m.references!==void 0||E.has(w)||c.push({name:w,plugin:L[w],required:m.required===!0,type:_(m.type),unique:m.unique===!0});return c},B=s=>{if(s instanceof p)return s;const c=s,w=c?.body?.code??c?.code??"AUTH_ADMIN_ERROR",m=c?.body?.message??c?.message??"auth admin operation failed";return new p(m,w)},j=(s,c={})=>{const w=s.$context,m=c.features??{},y=e=>{const a=new Set((e.plugins??[]).map(i=>i.id)),t=i=>a.has(i);return{accounts:m.accounts??!0,admin:m.admin??t("admin"),organization:m.organization??t("organization"),passkey:m.passkey??t("passkey"),twoFactor:m.twoFactor??t("two-factor")}},r=async e=>{try{return await e(await w)}catch(a){throw B(a)}},h=e=>u(e),g=async(e,a,t)=>{const i=t.where&&t.where.length>0?t.where:void 0,[n,o]=await Promise.all([e.adapter.findMany({limit:T(t.limit),model:a,offset:x(t.offset),sortBy:t.sortBy,where:i}),e.adapter.count({model:a,where:i})]);return{rows:n.map(d=>u(d)),total:o}};return{banUser:({expiresInSeconds:e,reason:a,userId:t})=>r(async i=>{let n=null;if(e!==void 0){if(!Number.isInteger(e)||e<=0)throw new p("expiresInSeconds must be a positive finite integer","INVALID_BAN_SECONDS");const d=Math.min(e,U);n=new Date(Date.now()+d*1e3)}const o=await i.internalAdapter.updateUser(t,{banExpires:n,banned:!0,banReason:a??"No reason"});return await i.internalAdapter.deleteUserSessions(t),h(o)}),cancelInvitation:({invitationId:e})=>r(async a=>{await a.adapter.delete({model:"invitation",where:[{field:"id",value:e}]})}),capabilities:()=>r(e=>Promise.resolve(y(e.options))),addMember:({organizationId:e,role:a,userId:t})=>r(async i=>{const n=await i.adapter.create({data:{createdAt:new Date,organizationId:e,role:a===void 0||a===""?"member":a,userId:t},model:"member"});return u(n)}),addTeamMember:({teamId:e,userId:a})=>r(async t=>{const i=await t.adapter.create({data:{createdAt:new Date,teamId:e,userId:a},model:"teamMember"});return u(i)}),config:()=>r(e=>{const a=e.options,t=y(a),i=new Set((a.plugins??[]).map(l=>l.id)),n=A(a),o=a.session??{},d=a.rateLimit??{};return Promise.resolve({capabilities:t,emailAndPassword:a.emailAndPassword?.enabled??!1,organization:{enabled:t.organization,roles:!!n.organizationRole,teams:!!n.team},plugins:[...i].toSorted((l,f)=>l.localeCompare(f)),rateLimit:{enabled:d.enabled??!1,max:d.max,window:d.window},session:{cookieCache:o.cookieCache?.enabled,expiresIn:o.expiresIn,freshAge:o.freshAge,updateAge:o.updateAge},socialProviders:Object.keys(a.socialProviders??{}).toSorted((l,f)=>l.localeCompare(f)),userFields:P(n.user?.fields??{})})}),createOrganization:({logo:e,metadata:a,name:t,ownerId:i,slug:n})=>r(async o=>{const d=b(n!==void 0&&n!==""?n:t);if(d==="")throw new p("could not derive a slug from the organization name","ORG_SLUG_INVALID");if(await o.adapter.findOne({model:"organization",where:[{field:"slug",value:d}]}))throw new p("an organization with this slug already exists","ORG_SLUG_TAKEN");const l=await o.adapter.create({data:{createdAt:new Date,logo:e===void 0||e===""?void 0:e,metadata:a===void 0?void 0:JSON.stringify(a),name:t,slug:d},model:"organization"});return i!==void 0&&i!==""&&await o.adapter.create({data:{createdAt:new Date,organizationId:l.id,role:"owner",userId:i},model:"member"}),u(l)}),createOrgRole:({organizationId:e,permission:a,role:t})=>r(async i=>{const n=await i.adapter.create({data:{createdAt:new Date,organizationId:e,permission:JSON.stringify(a),role:t},model:"organizationRole"});return u(n)}),createTeam:({name:e,organizationId:a})=>r(async t=>{const i=await t.adapter.create({data:{createdAt:new Date,name:e,organizationId:a},model:"team"});return u(i)}),deleteOrganization:({organizationId:e})=>r(async a=>{const t=A(a.options);if(await a.adapter.deleteMany({model:"member",where:[{field:"organizationId",value:e}]}),await a.adapter.deleteMany({model:"invitation",where:[{field:"organizationId",value:e}]}),t.team){const i=await a.adapter.findMany({model:"team",where:[{field:"organizationId",value:e}]});for(const n of i)await a.adapter.deleteMany({model:"teamMember",where:[{field:"teamId",value:n.id}]});await a.adapter.deleteMany({model:"team",where:[{field:"organizationId",value:e}]})}t.organizationRole&&await a.adapter.deleteMany({model:"organizationRole",where:[{field:"organizationId",value:e}]}),await a.adapter.delete({model:"organization",where:[{field:"id",value:e}]})}),deleteOrgRole:({roleId:e})=>r(async a=>{await a.adapter.delete({model:"organizationRole",where:[{field:"id",value:e}]})}),inviteMember:({email:e,inviterId:a,organizationId:t,role:i})=>r(async n=>{let o=a;if(o===void 0||o===""){const l=await n.adapter.findMany({model:"member",where:[{field:"organizationId",value:t}]});o=(l.find(f=>typeof f.role=="string"&&f.role.includes("owner"))??l[0])?.userId}if(o===void 0||o==="")throw new p("provide an inviter — the organization has no members to attribute the invitation to","INVITER_REQUIRED");const d=await n.adapter.create({data:{createdAt:new Date,email:e.toLowerCase(),expiresAt:new Date(Date.now()+N),inviterId:o,organizationId:t,role:i===void 0||i===""?"member":i,status:"pending"},model:"invitation"});return u(d)}),listOrgRoles:({limit:e,offset:a,organizationId:t})=>r(i=>g(i,"organizationRole",{limit:e,offset:a,sortBy:{direction:"desc",field:"createdAt"},where:[{field:"organizationId",value:t}]})),listTeamMembers:({limit:e,offset:a,teamId:t})=>r(i=>g(i,"teamMember",{limit:e,offset:a,where:[{field:"teamId",value:t}]})),listTeams:({limit:e,offset:a,organizationId:t})=>r(i=>g(i,"team",{limit:e,offset:a,sortBy:{direction:"desc",field:"createdAt"},where:[{field:"organizationId",value:t}]})),removeTeam:({teamId:e})=>r(async a=>{await a.adapter.deleteMany({model:"teamMember",where:[{field:"teamId",value:e}]}),await a.adapter.delete({model:"team",where:[{field:"id",value:e}]})}),removeTeamMember:({teamMemberId:e})=>r(async a=>{await a.adapter.delete({model:"teamMember",where:[{field:"id",value:e}]})}),updateMemberRole:({memberId:e,role:a})=>r(async t=>{const i=await t.adapter.update({model:"member",update:{role:I(a)},where:[{field:"id",value:e}]});return u(i??{id:e,role:I(a)})}),updateOrganization:({logo:e,metadata:a,name:t,organizationId:i,slug:n})=>r(async o=>{const d={};if(t!==void 0&&(d.name=t),n!==void 0&&n!==""&&(d.slug=b(n)),e!==void 0&&(d.logo=e===""?void 0:e),a!==void 0&&(d.metadata=JSON.stringify(a)),Object.keys(d).length===0)return u({id:i});const l=await o.adapter.update({model:"organization",update:d,where:[{field:"id",value:i}]});return u(l??{id:i})}),updateOrgRole:({permission:e,roleId:a})=>r(async t=>{const i=await t.adapter.update({model:"organizationRole",update:{permission:JSON.stringify(e),updatedAt:new Date},where:[{field:"id",value:a}]});return u(i??{id:a,permission:JSON.stringify(e)})}),updateTeam:({name:e,teamId:a})=>r(async t=>{const i=await t.adapter.update({model:"team",update:{name:e,updatedAt:new Date},where:[{field:"id",value:a}]});return u(i??{id:a,name:e})}),createUser:({data:e,email:a,name:t,password:i,role:n})=>r(async o=>{const d=a.toLowerCase();if(await o.internalAdapter.findUserByEmail(d))throw new p("a user with this email already exists","USER_ALREADY_EXISTS");const l=await o.internalAdapter.createUser({email:d,name:t,role:n===void 0?void 0:I(n),...e},{method:"admin"});if(i!==void 0&&i!==""){const f=await o.password.hash(i);await o.internalAdapter.linkAccount({issuer:S("credential"),password:f,providerAccountId:l.id,providerId:"credential",userId:l.id})}return h(l)}),deletePasskey:({passkeyId:e})=>r(async a=>{await a.adapter.delete({model:"passkey",where:[{field:"id",value:e}]})}),disableTwoFactor:({userId:e})=>r(async a=>{await a.adapter.deleteMany({model:"twoFactor",where:[{field:"userId",value:e}]}),await a.internalAdapter.updateUser(e,{twoFactorEnabled:!1})}),impersonateUser:({userId:e})=>r(async a=>{const t=await a.internalAdapter.findUserById(e);if(!t)throw new p("user not found","USER_NOT_FOUND");const i=c.impersonationSeconds;let n=z;if(i!==void 0){if(!Number.isInteger(i)||!Number.isFinite(i)||i<=0)throw new p("impersonationSeconds must be a positive finite integer","INVALID_IMPERSONATION_SECONDS");n=Math.min(i,R)}const o=new Date(Date.now()+n*1e3),d=await a.internalAdapter.createSession(e,!0,{expiresAt:o,impersonatedBy:c.impersonatedBy??e},!0);return{expiresAt:d.expiresAt instanceof Date?d.expiresAt.getTime():o.getTime(),token:d.token,user:h(t)}}),listAccounts:({userId:e})=>r(async a=>(await a.adapter.findMany({model:"account",where:[{field:"userId",value:e}]})).map(t=>u(t))),listInvitations:({limit:e,offset:a,organizationId:t})=>r(i=>g(i,"invitation",{limit:e,offset:a,where:[{field:"organizationId",value:t}]})),listMembers:({limit:e,offset:a,organizationId:t})=>r(i=>g(i,"member",{limit:e,offset:a,sortBy:{direction:"desc",field:"createdAt"},where:[{field:"organizationId",value:t}]})),listOrganizations:({limit:e,offset:a})=>r(t=>g(t,"organization",{limit:e,offset:a,sortBy:{direction:"desc",field:"createdAt"}})),listPasskeys:({userId:e})=>r(async a=>(await a.adapter.findMany({model:"passkey",where:[{field:"userId",value:e}]})).map(t=>u(t))),listSessions:({limit:e,offset:a,userId:t})=>r(i=>g(i,"session",{limit:e,offset:a,sortBy:{direction:"desc",field:"createdAt"},where:t===void 0||t===""?void 0:[{field:"userId",value:t}]})),listUsers:({filterField:e,filterValue:a,limit:t,offset:i,search:n,searchField:o,sortBy:d,sortDirection:l})=>r(f=>{const v=[];return n!==void 0&&n!==""&&v.push({field:o??"email",operator:"contains",value:n}),a!==void 0&&v.push({field:e??"email",operator:"eq",value:a}),g(f,"user",{limit:t,offset:i,sortBy:{direction:l??"desc",field:d??"createdAt"},where:v})}),removeMember:({memberId:e})=>r(async a=>{await a.adapter.delete({model:"member",where:[{field:"id",value:e}]})}),removeUser:({userId:e})=>r(async a=>{await a.internalAdapter.deleteUserSessions(e),await a.internalAdapter.deleteUser(e)}),revokeUserSession:({sessionId:e})=>r(async a=>{const t=await a.adapter.findOne({model:"session",where:[{field:"id",value:e}]});t?.token&&await a.internalAdapter.deleteSession(t.token)}),revokeUserSessions:({userId:e})=>r(async a=>{await a.internalAdapter.deleteUserSessions(e)}),setRole:({role:e,userId:a})=>r(async t=>{const i=await t.internalAdapter.updateUser(a,{role:I(e)});return h(i)}),setUserPassword:({newPassword:e,userId:a})=>r(async t=>{const i=t.password.config.minPasswordLength,n=t.password.config.maxPasswordLength;if(e.length<i)throw new p(`password must be at least ${i.toString()} characters`,"PASSWORD_TOO_SHORT");if(e.length>n)throw new p(`password must be at most ${n.toString()} characters`,"PASSWORD_TOO_LONG");const o=await t.password.hash(e);await t.internalAdapter.updatePassword(a,o)}),unbanUser:({userId:e})=>r(async a=>{const t=await a.internalAdapter.updateUser(e,{banExpires:null,banned:!1,banReason:null});return h(t)}),unlinkAccount:({accountId:e,userId:a})=>r(async t=>{await t.adapter.delete({model:"account",where:[{field:"id",value:e},{connector:"AND",field:"userId",value:a}]})}),updateUser:({data:e,userId:a})=>r(async t=>{const i=await t.internalAdapter.updateUser(a,e);return h(i)})}};export{p as LunoraAuthAdminError,j as createAuthAdmin};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{oauthProviderClient as u}from"@better-auth/oauth-provider/client";import{passkeyClient as m}from"@better-auth/passkey/client";import{oneTapClient as C,lastLoginMethodClient as c,deviceAuthorizationClient as p,anonymousClient as g,multiSessionClient as h,phoneNumberClient as d,usernameClient as L,adminClient as b,emailOTPClient as k,magicLinkClient as f,twoFactorClient as v,organizationClient as y}from"better-auth/client/plugins";const e={organization:y,twoFactor:v,passkey:m,magicLink:f,emailOtp:k,admin:b,username:L,phoneNumber:d,multiSession:h,anonymous:g,deviceAuthorization:p,lastLoginMethod:c,oauthProvider:u},P=(t={})=>{const i=[];for(const n of Object.keys(e))t[n]&&i.push(e[n]());return i},z=()=>globalThis.location?.origin,w=(t,i={})=>{const{baseURL:n,extraPlugins:a=[],oneTapClientId:o,plugins:l,...r}=i,s=o===void 0||o===""?[]:[C({clientId:o})];return t({...r,baseURL:n??z(),plugins:[...P(l),...s,...a]})};export{w as createLunoraAuthClient,P as lunoraAuthPlugins};
|
package/dist/plugins-client.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createLunoraAuthClient as n,lunoraAuthPlugins as t}from"./packem_shared/createLunoraAuthClient-
|
|
1
|
+
import{createLunoraAuthClient as n,lunoraAuthPlugins as t}from"./packem_shared/createLunoraAuthClient-gxLo2pKj.mjs";import{oauthProviderClient as l}from"@better-auth/oauth-provider/client";import{passkeyClient as C}from"@better-auth/passkey/client";import{adminClient as s,anonymousClient as m,customSessionClient as u,deviceAuthorizationClient as d,emailOTPClient as p,inferAdditionalFields as f,inferOrgAdditionalFields as h,jwtClient as c,lastLoginMethodClient as g,magicLinkClient as A,multiSessionClient as x,oneTapClient as T,oneTimeTokenClient as k,organizationClient as w,phoneNumberClient as F,siweClient as L,twoFactorClient as P,usernameClient as v}from"better-auth/client/plugins";export{s as adminClient,m as anonymousClient,n as createLunoraAuthClient,u as customSessionClient,d as deviceAuthorizationClient,p as emailOTPClient,f as inferAdditionalFields,h as inferOrgAdditionalFields,c as jwtClient,g as lastLoginMethodClient,t as lunoraAuthPlugins,A as magicLinkClient,x as multiSessionClient,l as oauthProviderClient,T as oneTapClient,k as oneTimeTokenClient,w as organizationClient,C as passkeyClient,F as phoneNumberClient,L as siweClient,P as twoFactorClient,v as usernameClient};
|
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.72",
|
|
4
4
|
"description": "Auth for Lunora — a thin better-auth wrapper: email/password, OAuth, plugins, D1-backed",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"auth",
|
|
@@ -102,9 +102,9 @@
|
|
|
102
102
|
"@better-auth/oauth-provider": "1.7.0-rc.2",
|
|
103
103
|
"@better-auth/passkey": "1.7.0-rc.2",
|
|
104
104
|
"@better-auth/scim": "1.7.0-rc.2",
|
|
105
|
-
"@lunora/errors": "1.0.0-alpha.
|
|
106
|
-
"@lunora/server": "1.0.0-alpha.
|
|
107
|
-
"@lunora/values": "1.0.0-alpha.
|
|
105
|
+
"@lunora/errors": "1.0.0-alpha.15",
|
|
106
|
+
"@lunora/server": "1.0.0-alpha.63",
|
|
107
|
+
"@lunora/values": "1.0.0-alpha.20",
|
|
108
108
|
"@visulima/disposable-email-domains": "1.0.1",
|
|
109
109
|
"@visulima/email-verifier": "1.0.1",
|
|
110
110
|
"@visulima/free-email-domains": "1.0.0",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{createLocalAccountIssuer as S}from"@better-auth/core/db";import{LunoraError as O}from"@lunora/errors";import{getAuthTables as A}from"better-auth/db";class p extends O{constructor(c,w){super(w,c,{name:"LunoraAuthAdminError"})}}const M=50,D=500,z=3600,R=z*24,U=100*365*24*60*60,N=2880*60*1e3,k=new Set(["accessToken","backupCodes","idToken","password","publicKey","refreshToken","secret","token"]),T=s=>Math.min(Math.max(Math.trunc(s??M),1),D),x=s=>Math.max(0,Math.trunc(s??0)),u=s=>{const c={};for(const[w,m]of Object.entries(s))k.has(w)||(c[w]=m instanceof Date?m.getTime():m);return c},I=s=>Array.isArray(s)?s.join(","):s,b=s=>s.toLowerCase().replaceAll(/[^\da-z]+/g,"-").replaceAll(/^-|-$/g,""),E=new Set(["banExpires","banned","banReason","createdAt","email","emailVerified","id","name","role","updatedAt"]),L={displayUsername:"username",phoneNumber:"phone-number",phoneNumberVerified:"phone-number",username:"username"},_=s=>s==="boolean"?"boolean":s==="date"?"date":s==="number"?"number":"string",P=s=>{const c=[];for(const[w,m]of Object.entries(s))m.input===!1||m.references!==void 0||E.has(w)||c.push({name:w,plugin:L[w],required:m.required===!0,type:_(m.type),unique:m.unique===!0});return c},B=s=>{if(s instanceof p)return s;const c=s,w=c?.body?.code??c?.code??"AUTH_ADMIN_ERROR",m=c?.body?.message??c?.message??"auth admin operation failed";return new p(m,w)},j=(s,c={})=>{const w=s.$context,m=c.features??{},y=e=>{const a=new Set((e.plugins??[]).map(i=>i.id)),t=i=>a.has(i);return{accounts:m.accounts??!0,admin:m.admin??t("admin"),organization:m.organization??t("organization"),passkey:m.passkey??t("passkey"),twoFactor:m.twoFactor??t("two-factor")}},r=async e=>{try{return await e(await w)}catch(a){throw B(a)}},h=e=>u(e),g=async(e,a,t)=>{const i=t.where&&t.where.length>0?t.where:void 0,[n,o]=await Promise.all([e.adapter.findMany({limit:T(t.limit),model:a,offset:x(t.offset),sortBy:t.sortBy,where:i}),e.adapter.count({model:a,where:i})]);return{rows:n.map(d=>u(d)),total:o}};return{banUser:({expiresInSeconds:e,reason:a,userId:t})=>r(async i=>{let n=null;if(e!==void 0){if(!Number.isInteger(e)||e<=0)throw new p("expiresInSeconds must be a positive finite integer","INVALID_BAN_SECONDS");const d=Math.min(e,U);n=new Date(Date.now()+d*1e3)}const o=await i.internalAdapter.updateUser(t,{banExpires:n,banned:!0,banReason:a??"No reason"});return await i.internalAdapter.deleteUserSessions(t),h(o)}),cancelInvitation:({invitationId:e})=>r(async a=>{await a.adapter.delete({model:"invitation",where:[{field:"id",value:e}]})}),capabilities:()=>r(e=>Promise.resolve(y(e.options))),addMember:({organizationId:e,role:a,userId:t})=>r(async i=>{const n=await i.adapter.create({data:{createdAt:new Date,organizationId:e,role:a===void 0||a===""?"member":a,userId:t},model:"member"});return u(n)}),addTeamMember:({teamId:e,userId:a})=>r(async t=>{const i=await t.adapter.create({data:{createdAt:new Date,teamId:e,userId:a},model:"teamMember"});return u(i)}),config:()=>r(e=>{const a=e.options,t=y(a),i=new Set((a.plugins??[]).map(l=>l.id)),n=A(a),o=a.session??{},d=a.rateLimit??{};return Promise.resolve({capabilities:t,emailAndPassword:a.emailAndPassword?.enabled??!1,organization:{enabled:t.organization,roles:!!n.organizationRole,teams:!!n.team},plugins:[...i].toSorted((l,f)=>l.localeCompare(f)),rateLimit:{enabled:d.enabled??!1,max:d.max,window:d.window},session:{cookieCache:o.cookieCache?.enabled,expiresIn:o.expiresIn,freshAge:o.freshAge,updateAge:o.updateAge},socialProviders:Object.keys(a.socialProviders??{}).toSorted((l,f)=>l.localeCompare(f)),userFields:P(n.user?.fields??{})})}),createOrganization:({logo:e,metadata:a,name:t,ownerId:i,slug:n})=>r(async o=>{const d=b(n!==void 0&&n!==""?n:t);if(d==="")throw new p("could not derive a slug from the organization name","ORG_SLUG_INVALID");if(await o.adapter.findOne({model:"organization",where:[{field:"slug",value:d}]}))throw new p("an organization with this slug already exists","ORG_SLUG_TAKEN");const l=await o.adapter.create({data:{createdAt:new Date,logo:e===void 0||e===""?void 0:e,metadata:a===void 0?void 0:JSON.stringify(a),name:t,slug:d},model:"organization"});return i!==void 0&&i!==""&&await o.adapter.create({data:{createdAt:new Date,organizationId:l.id,role:"owner",userId:i},model:"member"}),u(l)}),createOrgRole:({organizationId:e,permission:a,role:t})=>r(async i=>{const n=await i.adapter.create({data:{createdAt:new Date,organizationId:e,permission:JSON.stringify(a),role:t},model:"organizationRole"});return u(n)}),createTeam:({name:e,organizationId:a})=>r(async t=>{const i=await t.adapter.create({data:{createdAt:new Date,name:e,organizationId:a},model:"team"});return u(i)}),deleteOrganization:({organizationId:e})=>r(async a=>{const t=A(a.options);if(await a.adapter.deleteMany({model:"member",where:[{field:"organizationId",value:e}]}),await a.adapter.deleteMany({model:"invitation",where:[{field:"organizationId",value:e}]}),t.team){const i=await a.adapter.findMany({model:"team",where:[{field:"organizationId",value:e}]});for(const n of i)await a.adapter.deleteMany({model:"teamMember",where:[{field:"teamId",value:n.id}]});await a.adapter.deleteMany({model:"team",where:[{field:"organizationId",value:e}]})}t.organizationRole&&await a.adapter.deleteMany({model:"organizationRole",where:[{field:"organizationId",value:e}]}),await a.adapter.delete({model:"organization",where:[{field:"id",value:e}]})}),deleteOrgRole:({roleId:e})=>r(async a=>{await a.adapter.delete({model:"organizationRole",where:[{field:"id",value:e}]})}),inviteMember:({email:e,inviterId:a,organizationId:t,role:i})=>r(async n=>{let o=a;if(o===void 0||o===""){const l=await n.adapter.findMany({model:"member",where:[{field:"organizationId",value:t}]});o=(l.find(f=>typeof f.role=="string"&&f.role.includes("owner"))??l[0])?.userId}if(o===void 0||o==="")throw new p("provide an inviter — the organization has no members to attribute the invitation to","INVITER_REQUIRED");const d=await n.adapter.create({data:{createdAt:new Date,email:e.toLowerCase(),expiresAt:new Date(Date.now()+N),inviterId:o,organizationId:t,role:i===void 0||i===""?"member":i,status:"pending"},model:"invitation"});return u(d)}),listOrgRoles:({limit:e,offset:a,organizationId:t})=>r(i=>g(i,"organizationRole",{limit:e,offset:a,sortBy:{direction:"desc",field:"createdAt"},where:[{field:"organizationId",value:t}]})),listTeamMembers:({limit:e,offset:a,teamId:t})=>r(i=>g(i,"teamMember",{limit:e,offset:a,where:[{field:"teamId",value:t}]})),listTeams:({limit:e,offset:a,organizationId:t})=>r(i=>g(i,"team",{limit:e,offset:a,sortBy:{direction:"desc",field:"createdAt"},where:[{field:"organizationId",value:t}]})),removeTeam:({teamId:e})=>r(async a=>{await a.adapter.deleteMany({model:"teamMember",where:[{field:"teamId",value:e}]}),await a.adapter.delete({model:"team",where:[{field:"id",value:e}]})}),removeTeamMember:({teamMemberId:e})=>r(async a=>{await a.adapter.delete({model:"teamMember",where:[{field:"id",value:e}]})}),updateMemberRole:({memberId:e,role:a})=>r(async t=>{const i=await t.adapter.update({model:"member",update:{role:I(a)},where:[{field:"id",value:e}]});return u(i??{id:e,role:I(a)})}),updateOrganization:({logo:e,metadata:a,name:t,organizationId:i,slug:n})=>r(async o=>{const d={};if(t!==void 0&&(d.name=t),n!==void 0&&n!==""&&(d.slug=b(n)),e!==void 0&&(d.logo=e===""?void 0:e),a!==void 0&&(d.metadata=JSON.stringify(a)),Object.keys(d).length===0)return u({id:i});const l=await o.adapter.update({model:"organization",update:d,where:[{field:"id",value:i}]});return u(l??{id:i})}),updateOrgRole:({permission:e,roleId:a})=>r(async t=>{const i=await t.adapter.update({model:"organizationRole",update:{permission:JSON.stringify(e),updatedAt:new Date},where:[{field:"id",value:a}]});return u(i??{id:a,permission:JSON.stringify(e)})}),updateTeam:({name:e,teamId:a})=>r(async t=>{const i=await t.adapter.update({model:"team",update:{name:e,updatedAt:new Date},where:[{field:"id",value:a}]});return u(i??{id:a,name:e})}),createUser:({data:e,email:a,name:t,password:i,role:n})=>r(async o=>{const d=a.toLowerCase();if(await o.internalAdapter.findUserByEmail(d))throw new p("a user with this email already exists","USER_ALREADY_EXISTS");const l=await o.internalAdapter.createUser({email:d,name:t,role:n===void 0?void 0:I(n),...e},{method:"admin"});if(i!==void 0&&i!==""){const f=await o.password.hash(i);await o.internalAdapter.linkAccount({issuer:S("credential"),password:f,providerAccountId:l.id,providerId:"credential",userId:l.id})}return h(l)}),deletePasskey:({passkeyId:e})=>r(async a=>{await a.adapter.delete({model:"passkey",where:[{field:"id",value:e}]})}),disableTwoFactor:({userId:e})=>r(async a=>{await a.adapter.deleteMany({model:"twoFactor",where:[{field:"userId",value:e}]}),await a.internalAdapter.updateUser(e,{twoFactorEnabled:!1})}),impersonateUser:({userId:e})=>r(async a=>{const t=await a.internalAdapter.findUserById(e);if(!t)throw new p("user not found","USER_NOT_FOUND");const i=c.impersonationSeconds;let n=z;if(i!==void 0){if(!Number.isInteger(i)||!Number.isFinite(i)||i<=0)throw new p("impersonationSeconds must be a positive finite integer","INVALID_IMPERSONATION_SECONDS");n=Math.min(i,R)}const o=new Date(Date.now()+n*1e3),d=await a.internalAdapter.createSession(e,!0,{expiresAt:o,impersonatedBy:c.impersonatedBy??e},!0);return{expiresAt:d.expiresAt instanceof Date?d.expiresAt.getTime():o.getTime(),token:d.token,user:h(t)}}),listAccounts:({userId:e})=>r(async a=>(await a.adapter.findMany({model:"account",where:[{field:"userId",value:e}]})).map(t=>u(t))),listInvitations:({limit:e,offset:a,organizationId:t})=>r(i=>g(i,"invitation",{limit:e,offset:a,where:[{field:"organizationId",value:t}]})),listMembers:({limit:e,offset:a,organizationId:t})=>r(i=>g(i,"member",{limit:e,offset:a,sortBy:{direction:"desc",field:"createdAt"},where:[{field:"organizationId",value:t}]})),listOrganizations:({limit:e,offset:a})=>r(t=>g(t,"organization",{limit:e,offset:a,sortBy:{direction:"desc",field:"createdAt"}})),listPasskeys:({userId:e})=>r(async a=>(await a.adapter.findMany({model:"passkey",where:[{field:"userId",value:e}]})).map(t=>u(t))),listSessions:({limit:e,offset:a,userId:t})=>r(i=>g(i,"session",{limit:e,offset:a,sortBy:{direction:"desc",field:"createdAt"},where:t===void 0||t===""?void 0:[{field:"userId",value:t}]})),listUsers:({filterField:e,filterValue:a,limit:t,offset:i,search:n,searchField:o,sortBy:d,sortDirection:l})=>r(f=>{const v=[];return n!==void 0&&n!==""&&v.push({field:o??"email",operator:"contains",value:n}),a!==void 0&&v.push({field:e??"email",operator:"eq",value:a}),g(f,"user",{limit:t,offset:i,sortBy:{direction:l??"desc",field:d??"createdAt"},where:v})}),removeMember:({memberId:e})=>r(async a=>{await a.adapter.delete({model:"member",where:[{field:"id",value:e}]})}),removeUser:({userId:e})=>r(async a=>{await a.internalAdapter.deleteUserSessions(e),await a.internalAdapter.deleteUser(e)}),revokeUserSession:({sessionId:e})=>r(async a=>{const t=await a.adapter.findOne({model:"session",where:[{field:"id",value:e}]});t?.token&&await a.internalAdapter.deleteSession(t.token)}),revokeUserSessions:({userId:e})=>r(async a=>{await a.internalAdapter.deleteUserSessions(e)}),setRole:({role:e,userId:a})=>r(async t=>{const i=await t.internalAdapter.updateUser(a,{role:I(e)});return h(i)}),setUserPassword:({newPassword:e,userId:a})=>r(async t=>{const i=t.password.config.minPasswordLength,n=t.password.config.maxPasswordLength;if(e.length<i)throw new p(`password must be at least ${i.toString()} characters`,"PASSWORD_TOO_SHORT");if(e.length>n)throw new p(`password must be at most ${n.toString()} characters`,"PASSWORD_TOO_LONG");const o=await t.password.hash(e);await t.internalAdapter.updatePassword(a,o)}),unbanUser:({userId:e})=>r(async a=>{const t=await a.internalAdapter.updateUser(e,{banExpires:null,banned:!1,banReason:null});return h(t)}),unlinkAccount:({accountId:e,userId:a})=>r(async t=>{await t.adapter.delete({model:"account",where:[{field:"id",value:e},{connector:"AND",field:"userId",value:a}]})}),updateUser:({data:e,userId:a})=>r(async t=>{const i=await t.internalAdapter.updateUser(a,e);return h(i)})}};export{p as LunoraAuthAdminError,j as createAuthAdmin};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{oauthProviderClient as l}from"@better-auth/oauth-provider/client";import{passkeyClient as r}from"@better-auth/passkey/client";import{oneTapClient as p,organizationClient as h,twoFactorClient as m,magicLinkClient as C,emailOTPClient as c,adminClient as g,usernameClient as d,phoneNumberClient as L,multiSessionClient as b,anonymousClient as k,deviceAuthorizationClient as v,lastLoginMethodClient as y}from"better-auth/client/plugins";const P=(t={})=>{const n=[];return t.organization&&n.push(h()),t.twoFactor&&n.push(m()),t.passkey&&n.push(r()),t.magicLink&&n.push(C()),t.emailOtp&&n.push(c()),t.admin&&n.push(g()),t.username&&n.push(d()),t.phoneNumber&&n.push(L()),t.multiSession&&n.push(b()),t.anonymous&&n.push(k()),t.deviceAuthorization&&n.push(v()),t.lastLoginMethod&&n.push(y()),t.oauthProvider&&n.push(l()),n},z=()=>globalThis.location?.origin,w=(t,n={})=>{const{baseURL:o,extraPlugins:i=[],oneTapClientId:e,plugins:s,...a}=n,u=e===void 0||e===""?[]:[p({clientId:e})];return t({...a,baseURL:o??z(),plugins:[...P(s),...u,...i]})};export{w as createLunoraAuthClient,P as lunoraAuthPlugins};
|