@lunora/auth 1.0.0-alpha.162 → 1.0.0-alpha.164

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 CHANGED
@@ -1,4 +1,4 @@
1
- import{standardRules as f,piiRules as g,redact as R}from"@visulima/redact";const c="__lunora_auth_audit__",N=[...f,...g],h=1e3,p=1e4,n=null,d=e=>{if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="bigint"||typeof e=="boolean")return String(e)},I=async e=>{await e.run(`CREATE TABLE IF NOT EXISTS "${c}" (
1
+ import{standardRules as D,piiRules as b,redact as $}from"@visulima/redact";const w=new Set(["auth","authorization","bearer","card","cc","cookie","credential","cvc","cvv","dsn","hmac","hotp","iban","jwt","kek","mnemonic","otp","pass","passcode","passphrase","passwd","password","pem","pin","pwd","salt","secret","session","sid","sig","signature","ssn","token","totp","verifier"]),C=new Set(["card","pass","pin","session"]),k=new Set(["access","api","client","encryption","master","priv","private","secret","signing"]),M=new Set(["2fa","auth","authorization","backup","factor","hotp","mfa","otp","pin","recovery","reset","security","totp","verification","verify"]),U=new Set(["card no","connection string","database url","one time"]),W=["accesskey","apikey","authorization","cookie","credential","mfacode","otpcode","passcode","passphrase","passwd","password","privatekey","secret","secretkey","sessionid","signature","token"],X=new Set(["again","b64","base","base64","bytes","confirm","confirmation","data","digest","encrypted","hash","hashed","header","hex","id","input","key","no","num","number","plain","plaintext","raw","repeat","str","string","text","value"]),F=new Set(["count","counts","length","limit","limits","size","tokens","total","usage"]),j=new Set(["max","min","num","total"]),S=4096,q=16384,d="<REDACTED>",x="[redaction budget exceeded]",z=t=>t.replaceAll(/([a-z\d])([A-Z])/g,"$1 $2").replaceAll(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").toLowerCase().split(/[^a-z\d]+/).filter(e=>e.length>0),I=t=>t.length>3&&t.endsWith("s")&&!t.endsWith("ss")?t.slice(0,-1):t,B=(t,e)=>{const s=I(t[e]),n=e>0?I(t[e-1]):void 0;if(w.has(s))return s;if(n!==void 0){if(s==="key"&&k.has(n))return"key";if(s==="code"&&M.has(n))return"code";if(U.has(`${n} ${s}`))return`${n} ${s}`}return W.some(r=>s.endsWith(r))?s:void 0},R=t=>{const e=z(t);if(e.length===0)return"none";const s=F.has(e.at(-1))||j.has(e[0]);for(let n=e.length-1;n>=0;n-=1){const r=B(e,n);if(r!==void 0)return s?"count-secret":e.slice(n+1).every(a=>X.has(a))?C.has(r)&&n===e.length-1?"scalar-secret":"secret":"none"}return"none"},K=t=>typeof t=="boolean"||t===null||t===void 0?t:d,P=t=>{const e=t.indexOf("://")+3,s=t.slice(e),n=s.split(/[?#]/,1)[0],r=n.lastIndexOf("@"),a=n.indexOf(":"),c=n.indexOf("/"),i=a!==-1&&/^\d+$/.test(n.slice(a+1,c===-1?void 0:c)),o=a!==-1&&!i&&(c===-1||a<c);if(r===-1&&o&&s.includes("@",n.length))return t.slice(0,e);const l=r!==-1&&(c===-1||r<c||a!==-1&&a<r&&!i);return`${t.slice(0,e)}${l?n.slice(r+1):n}`},G=/\b[a-z][\d+.a-z-]{1,15}:\/\/[^\s"'<>()[\]{}]+/gi,V=/-----BEGIN ([A-Z ]{0,32}PRIVATE KEY)-----[\s\S]*?(?:-----END [A-Z ]{0,32}PRIVATE KEY-----|$)/g,Y=/\b(Basic|Bearer|Digest)\s+[\w+/=.~-]{4,}|\beyJ[\w-]{2,}\.[\w-]{2,}\.[\w-]*|\bAKIA[\dA-Z]{16}\b/g,H=/(\s|^)(-u|--user|--password|--pass|--token|--api-key)(\s+|=)[^\s"']+/g,f=/(?<![\w.-])(\\?["']?)([A-Za-z_][\w.-]{0,63})\1[ \t]{0,4}([:=])[ \t]{0,4}/g,L=/(?:basic|bearer|digest|token)\s+[^\s"&'),;\]}]+|\\"(?:[^"\\\n]|\\[^"])*(?:\\")?|"[^\n"]*"?|'[^\n']*'?|[^\s"&'),;\]}]+/iy,N=/(?:[ \t]+(?![A-Za-z_][\w.-]{0,63}[:=])[^\s,;)\]}]+)*/y,Z=t=>{let e="",s=0;f.lastIndex=0;for(let n=f.exec(t);n!==null;n=f.exec(t)){const r=R(n[2]),a=n.index+n[0].length;L.lastIndex=a;const c=r==="none"?null:L.exec(t);if(c===null||r==="count-secret"&&/^["']?[\d.]+["']?$/.test(c[0])){f.lastIndex=Math.max(a,n.index+1);continue}const i=c[0],o=i.startsWith('\\"')?'\\"':i.startsWith('"')||i.startsWith("'")?i[0]:"";let l=a+i.length;o===""&&n[3]===":"&&(N.lastIndex=l,l+=N.exec(t)?.[0].length??0),e+=`${t.slice(s,a)}${o}${d}${i.length>o.length&&i.endsWith(o)?o:""}`,s=l,f.lastIndex=s}return e+t.slice(s)},v=/[:=@]|basic|bearer|digest|eyJ|AKIA|-u\b|--/i,J=(t,e)=>{if(e.remaining<=0)return x;const s=t.length>S?`${t.slice(0,S)}…[truncated]`:t;return e.remaining-=s.length,v.test(s)?Z(s.replaceAll(V,`-----BEGIN $1-----${d}`).replaceAll(G,P).replaceAll(Y,(n,r)=>r===void 0?d:`${r} ${d}`).replaceAll(H,`$1$2$3${d}`)):s},Q=t=>t instanceof Error||t instanceof RegExp||t instanceof Map||t instanceof Set||t instanceof WeakMap||t instanceof WeakSet||t instanceof Promise||t instanceof ArrayBuffer||ArrayBuffer.isView(t),p=Symbol("no-json"),tt=t=>{const{toJSON:e}=t;if(typeof e!="function")return p;try{const s=e.call(t);return s===t?p:s}catch{return p}},et=32,T=(t,e,s,n,r)=>{if(typeof t=="string")return n?d:J(t,r);if(typeof t!="object"||t===null||!Array.isArray(t)&&Q(t))return t;if(e.has(t)||s>=et)return d;const a=Array.isArray(t)?p:tt(t);if(a!==p){e.add(t);const i=T(a,e,s+1,n,r);return e.delete(t),i}e.add(t);const c=Array.isArray(t)?t.map(i=>T(i,e,s+1,n,r)):Object.fromEntries(Object.entries(t).map(([i,o])=>{const l=R(i);return l==="secret"||l==="scalar-secret"&&(typeof o!="object"||o===null)?[i,K(o)]:[i,T(o,e,s+1,l==="count-secret"&&(typeof o=="string"||Array.isArray(o)),r)]}));return e.delete(t),c},st=t=>T(t,new WeakSet,0,!1,{remaining:q}),u="__lunora_auth_audit__",nt=[...D,...b],rt=1e3,it=1e4,A=null,h=t=>{if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="bigint"||typeof t=="boolean")return String(t)},at=async t=>{await t.run(`CREATE TABLE IF NOT EXISTS "${u}" (
2
2
  seq INTEGER PRIMARY KEY AUTOINCREMENT,
3
3
  ts REAL NOT NULL,
4
4
  event TEXT NOT NULL,
@@ -9,4 +9,4 @@ import{standardRules as f,piiRules as g,redact as R}from"@visulima/redact";const
9
9
  ip TEXT,
10
10
  user_agent TEXT,
11
11
  detail TEXT
12
- )`,[]);try{await e.run(`ALTER TABLE "${c}" ADD COLUMN target_email TEXT`,[])}catch(t){if(!(t instanceof Error?t.message.toLowerCase():String(t).toLowerCase()).includes("duplicate column"))throw t}},l=new WeakMap,m=e=>{const t=l.get(e);if(t)return t;const a=I(e);return l.set(e,a),a.catch(()=>l.delete(e)),a},D=async(e,t,a={})=>{await m(e);let i;return t.detail!==void 0&&(i=a.redactDetail===!1?t.detail:R(t.detail,N)),await e.run(`INSERT INTO "${c}" (ts, event, outcome, actor_id, actor_email, target_email, ip, user_agent, detail) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[t.ts,t.event,t.outcome,t.actorId??n,t.actorEmail??n,t.targetEmail??n,t.ip??n,t.userAgent??n,i===void 0?n:JSON.stringify(i)]),typeof a.retention=="number"&&a.retention>0&&await e.run(`DELETE FROM "${c}" WHERE seq <= (SELECT MAX(seq) - ? FROM "${c}")`,[a.retention]),{...t,detail:i}},S=async(e,t={})=>{await m(e);const a=Number.isFinite(t.limit)?Math.max(1,Math.min(t.limit,p)):h,i=["seq > ?"],o=[t.sinceSeq??0],A=t.sinceSeq===void 0?"DESC":"ASC";return t.actorId!==void 0&&(i.push("actor_id = ?"),o.push(t.actorId)),t.event!==void 0&&(i.push("event = ?"),o.push(t.event)),o.push(a),(await e.all(`SELECT seq, ts, event, outcome, actor_id, actor_email, target_email, ip, user_agent, detail FROM "${c}" WHERE ${i.join(" AND ")} ORDER BY seq ${A} LIMIT ?`,o)).map(r=>{const u={event:d(r.event)??"",outcome:r.outcome==="failure"?"failure":"success",seq:Number(r.seq),ts:Number(r.ts)},_=[["actorId","actor_id"],["actorEmail","actor_email"],["targetEmail","target_email"],["ip","ip"],["userAgent","user_agent"]];for(const[s,L]of _){const T=d(r[L]);T!==void 0&&(u[s]=T)}const E=d(r.detail);if(E!==void 0)try{const s=JSON.parse(E);typeof s=="object"&&s!==null&&!Array.isArray(s)&&(u.detail=s)}catch{}return u})},O=e=>({read:t=>S(e,t)});export{c as AUTH_AUDIT_TABLE,D as appendAuthAuditEntry,O as createAuthAuditReader,m as ensureAuthAuditTable,S as readAuthAuditLog};
12
+ )`,[]);try{await t.run(`ALTER TABLE "${u}" ADD COLUMN target_email TEXT`,[])}catch(e){if(!(e instanceof Error?e.message.toLowerCase():String(e).toLowerCase()).includes("duplicate column"))throw e}},m=new WeakMap,y=t=>{const e=m.get(t);if(e)return e;const s=at(t);return m.set(t,s),s.catch(()=>m.delete(t)),s},lt=async(t,e,s={})=>{await y(t);let n;return e.detail!==void 0&&(n=s.redactDetail===!1?e.detail:$(st(e.detail),nt)),await t.run(`INSERT INTO "${u}" (ts, event, outcome, actor_id, actor_email, target_email, ip, user_agent, detail) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[e.ts,e.event,e.outcome,e.actorId??A,e.actorEmail??A,e.targetEmail??A,e.ip??A,e.userAgent??A,n===void 0?A:JSON.stringify(n)]),typeof s.retention=="number"&&s.retention>0&&await t.run(`DELETE FROM "${u}" WHERE seq <= (SELECT MAX(seq) - ? FROM "${u}")`,[s.retention]),{...e,detail:n}},ot=async(t,e={})=>{await y(t);const s=Number.isFinite(e.limit)?Math.max(1,Math.min(e.limit,it)):rt,n=["seq > ?"],r=[e.sinceSeq??0],a=e.sinceSeq===void 0?"DESC":"ASC";return e.actorId!==void 0&&(n.push("actor_id = ?"),r.push(e.actorId)),e.event!==void 0&&(n.push("event = ?"),r.push(e.event)),r.push(s),(await t.all(`SELECT seq, ts, event, outcome, actor_id, actor_email, target_email, ip, user_agent, detail FROM "${u}" WHERE ${n.join(" AND ")} ORDER BY seq ${a} LIMIT ?`,r)).map(i=>{const o={event:h(i.event)??"",outcome:i.outcome==="failure"?"failure":"success",seq:Number(i.seq),ts:Number(i.ts)},l=[["actorId","actor_id"],["actorEmail","actor_email"],["targetEmail","target_email"],["ip","ip"],["userAgent","user_agent"]];for(const[E,O]of l){const g=h(i[O]);g!==void 0&&(o[E]=g)}const _=h(i.detail);if(_!==void 0)try{const E=JSON.parse(_);typeof E=="object"&&E!==null&&!Array.isArray(E)&&(o.detail=E)}catch{}return o})},dt=t=>({read:e=>ot(t,e)});export{u as AUTH_AUDIT_TABLE,lt as appendAuthAuditEntry,dt as createAuthAuditReader,y as ensureAuthAuditTable,ot as readAuthAuditLog};
package/dist/index.d.mts CHANGED
@@ -847,11 +847,18 @@ declare const authDoSchemaStatements: (options: LunoraAuthOptions) => string[];
847
847
  declare const authDoColumnAdditions: (options: LunoraAuthOptions, existingColumns: (table: string) => Iterable<string>) => string[];
848
848
  /** The slice of a Durable Object namespace this needs — structural, so tests need no runtime. */
849
849
  interface AuthNamespaceLike {
850
- get: (id: unknown) => {
850
+ get(this: void, id: unknown): {
851
851
  fetch: (request: Request) => Promise<Response>;
852
852
  };
853
- idFromName: (name: string) => unknown;
853
+ idFromName(this: void, name: string): unknown;
854
+ /** Jurisdiction-restricted subnamespace. Optional only so older binding types still fit; {@link createDoAuthWiring} fails closed without it when a jurisdiction is set. */
855
+ jurisdiction?(this: void, jurisdiction: AuthJurisdiction): AuthNamespaceLike;
854
856
  }
857
+ /**
858
+ * Cloudflare Durable Object data-residency jurisdiction. Widening union —
859
+ * Cloudflare adds values over time.
860
+ */
861
+ type AuthJurisdiction = "eu" | "fedramp" | "us";
855
862
  /** What {@link createDoAuthWiring} needs, already resolved against `env`. */
856
863
  interface DoAuthWiringOptions {
857
864
  /**
@@ -859,6 +866,14 @@ interface DoAuthWiringOptions {
859
866
  * means identity resolution fails closed — see {@link DoAuthWiring.resolveIdentity}.
860
867
  */
861
868
  internalSecret: string | undefined;
869
+ /**
870
+ * Pin the auth object to a data-residency jurisdiction — pass the worker's
871
+ * `jurisdiction`. The object holds users, sessions, and credentials, so it must
872
+ * live where the rest of the app's data does. The same name maps to a different
873
+ * object per jurisdiction, so toggling this on an existing deployment starts a
874
+ * fresh, empty auth object.
875
+ */
876
+ jurisdiction?: AuthJurisdiction;
862
877
  /** The bound namespace, or `undefined` when the binding is absent from `env`. */
863
878
  namespace: AuthNamespaceLike | undefined;
864
879
  /**
@@ -912,6 +927,7 @@ interface DoAuthWiring {
912
927
  * Every failure path answers "not authenticated" rather than throwing: this runs on
913
928
  * the request path for every request that touches `ctx.auth`, and a throw there would
914
929
  * turn a misconfiguration into a 500 on traffic that has nothing to do with auth.
930
+ * The exception is a `jurisdiction` the namespace cannot express, which throws here.
915
931
  * @param options The resolved namespace, secret, and names.
916
932
  * @returns The `authHandler` / `resolveIdentity` pair.
917
933
  * @experimental
@@ -1076,4 +1092,4 @@ declare const validateSessionPolicy: (policy: SessionPolicy) => SessionPolicy;
1076
1092
  * with the same 60s cookie cache as `rolling`.
1077
1093
  */
1078
1094
  declare const sessionPresets: Record<"longLived" | "rolling" | "strict", SessionPolicy>;
1079
- 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 AuthAccount, type AuthAdmin, type AuthAdminSession, type AuthAdminUser, type AuthAuditEvent, type AuthAuditHookConfig, type AuthAuditReader, type AuthCapabilities, type AuthConfigInfo, type AuthDoOptions, type AuthDoState, type AuthInvitation, type AuthMember, type AuthNamespaceLike, type AuthOrgRole, type AuthOrganization, type AuthPage, type AuthPasskey, type AuthSignUpInvitation, type AuthTeam, type AuthTeamMember, type AuthTimestamp, type AuthUserFieldSpec, type CreateAuthAdminOptions, DEFAULT_AUTH_BASE_PATH, type DoAuthWiring, type DoAuthWiringOptions, type EmailClassification, type EmailGateConfig, type EmailGateHookConfig, type ImpersonationResult, type ListUsersOptions, type LunoraAuth, LunoraAuthAdminError, LunoraAuthDO, type LunoraAuthOptions, type SessionPolicy, type SqlExecutor, authAuditHook, authDoColumnAdditions, authDoSchemaStatements, buildAuditEntry, compileMigrationsSql, createAuthAdmin, createDoAuthWiring, emailGateDatabaseHooks, ensureMigrated, eventForPath, handleAuthRequest, legacyIssuerCleanupStatements, sessionPresets, validateSessionPolicy, withAuthAudit, withEmailGate };
1095
+ 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 AuthAccount, type AuthAdmin, type AuthAdminSession, type AuthAdminUser, type AuthAuditEvent, type AuthAuditHookConfig, type AuthAuditReader, type AuthCapabilities, type AuthConfigInfo, type AuthDoOptions, type AuthDoState, type AuthInvitation, type AuthJurisdiction, type AuthMember, type AuthNamespaceLike, type AuthOrgRole, type AuthOrganization, type AuthPage, type AuthPasskey, type AuthSignUpInvitation, type AuthTeam, type AuthTeamMember, type AuthTimestamp, type AuthUserFieldSpec, type CreateAuthAdminOptions, DEFAULT_AUTH_BASE_PATH, type DoAuthWiring, type DoAuthWiringOptions, type EmailClassification, type EmailGateConfig, type EmailGateHookConfig, type ImpersonationResult, type ListUsersOptions, type LunoraAuth, LunoraAuthAdminError, LunoraAuthDO, type LunoraAuthOptions, type SessionPolicy, type SqlExecutor, authAuditHook, authDoColumnAdditions, authDoSchemaStatements, buildAuditEntry, compileMigrationsSql, createAuthAdmin, createDoAuthWiring, emailGateDatabaseHooks, ensureMigrated, eventForPath, handleAuthRequest, legacyIssuerCleanupStatements, sessionPresets, validateSessionPolicy, withAuthAudit, withEmailGate };
package/dist/index.d.ts CHANGED
@@ -847,11 +847,18 @@ declare const authDoSchemaStatements: (options: LunoraAuthOptions) => string[];
847
847
  declare const authDoColumnAdditions: (options: LunoraAuthOptions, existingColumns: (table: string) => Iterable<string>) => string[];
848
848
  /** The slice of a Durable Object namespace this needs — structural, so tests need no runtime. */
849
849
  interface AuthNamespaceLike {
850
- get: (id: unknown) => {
850
+ get(this: void, id: unknown): {
851
851
  fetch: (request: Request) => Promise<Response>;
852
852
  };
853
- idFromName: (name: string) => unknown;
853
+ idFromName(this: void, name: string): unknown;
854
+ /** Jurisdiction-restricted subnamespace. Optional only so older binding types still fit; {@link createDoAuthWiring} fails closed without it when a jurisdiction is set. */
855
+ jurisdiction?(this: void, jurisdiction: AuthJurisdiction): AuthNamespaceLike;
854
856
  }
857
+ /**
858
+ * Cloudflare Durable Object data-residency jurisdiction. Widening union —
859
+ * Cloudflare adds values over time.
860
+ */
861
+ type AuthJurisdiction = "eu" | "fedramp" | "us";
855
862
  /** What {@link createDoAuthWiring} needs, already resolved against `env`. */
856
863
  interface DoAuthWiringOptions {
857
864
  /**
@@ -859,6 +866,14 @@ interface DoAuthWiringOptions {
859
866
  * means identity resolution fails closed — see {@link DoAuthWiring.resolveIdentity}.
860
867
  */
861
868
  internalSecret: string | undefined;
869
+ /**
870
+ * Pin the auth object to a data-residency jurisdiction — pass the worker's
871
+ * `jurisdiction`. The object holds users, sessions, and credentials, so it must
872
+ * live where the rest of the app's data does. The same name maps to a different
873
+ * object per jurisdiction, so toggling this on an existing deployment starts a
874
+ * fresh, empty auth object.
875
+ */
876
+ jurisdiction?: AuthJurisdiction;
862
877
  /** The bound namespace, or `undefined` when the binding is absent from `env`. */
863
878
  namespace: AuthNamespaceLike | undefined;
864
879
  /**
@@ -912,6 +927,7 @@ interface DoAuthWiring {
912
927
  * Every failure path answers "not authenticated" rather than throwing: this runs on
913
928
  * the request path for every request that touches `ctx.auth`, and a throw there would
914
929
  * turn a misconfiguration into a 500 on traffic that has nothing to do with auth.
930
+ * The exception is a `jurisdiction` the namespace cannot express, which throws here.
915
931
  * @param options The resolved namespace, secret, and names.
916
932
  * @returns The `authHandler` / `resolveIdentity` pair.
917
933
  * @experimental
@@ -1076,4 +1092,4 @@ declare const validateSessionPolicy: (policy: SessionPolicy) => SessionPolicy;
1076
1092
  * with the same 60s cookie cache as `rolling`.
1077
1093
  */
1078
1094
  declare const sessionPresets: Record<"longLived" | "rolling" | "strict", SessionPolicy>;
1079
- 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 AuthAccount, type AuthAdmin, type AuthAdminSession, type AuthAdminUser, type AuthAuditEvent, type AuthAuditHookConfig, type AuthAuditReader, type AuthCapabilities, type AuthConfigInfo, type AuthDoOptions, type AuthDoState, type AuthInvitation, type AuthMember, type AuthNamespaceLike, type AuthOrgRole, type AuthOrganization, type AuthPage, type AuthPasskey, type AuthSignUpInvitation, type AuthTeam, type AuthTeamMember, type AuthTimestamp, type AuthUserFieldSpec, type CreateAuthAdminOptions, DEFAULT_AUTH_BASE_PATH, type DoAuthWiring, type DoAuthWiringOptions, type EmailClassification, type EmailGateConfig, type EmailGateHookConfig, type ImpersonationResult, type ListUsersOptions, type LunoraAuth, LunoraAuthAdminError, LunoraAuthDO, type LunoraAuthOptions, type SessionPolicy, type SqlExecutor, authAuditHook, authDoColumnAdditions, authDoSchemaStatements, buildAuditEntry, compileMigrationsSql, createAuthAdmin, createDoAuthWiring, emailGateDatabaseHooks, ensureMigrated, eventForPath, handleAuthRequest, legacyIssuerCleanupStatements, sessionPresets, validateSessionPolicy, withAuthAudit, withEmailGate };
1095
+ 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 AuthAccount, type AuthAdmin, type AuthAdminSession, type AuthAdminUser, type AuthAuditEvent, type AuthAuditHookConfig, type AuthAuditReader, type AuthCapabilities, type AuthConfigInfo, type AuthDoOptions, type AuthDoState, type AuthInvitation, type AuthJurisdiction, type AuthMember, type AuthNamespaceLike, type AuthOrgRole, type AuthOrganization, type AuthPage, type AuthPasskey, type AuthSignUpInvitation, type AuthTeam, type AuthTeamMember, type AuthTimestamp, type AuthUserFieldSpec, type CreateAuthAdminOptions, DEFAULT_AUTH_BASE_PATH, type DoAuthWiring, type DoAuthWiringOptions, type EmailClassification, type EmailGateConfig, type EmailGateHookConfig, type ImpersonationResult, type ListUsersOptions, type LunoraAuth, LunoraAuthAdminError, LunoraAuthDO, type LunoraAuthOptions, type SessionPolicy, type SqlExecutor, authAuditHook, authDoColumnAdditions, authDoSchemaStatements, buildAuditEntry, compileMigrationsSql, createAuthAdmin, createDoAuthWiring, emailGateDatabaseHooks, ensureMigrated, eventForPath, handleAuthRequest, 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-CG0Yv85f.mjs";import{LunoraAuthAdminError as A,createAuthAdmin as u}from"./packem_shared/LunoraAuthAdminError-uhKG1MgQ.mjs";import{AUTH_AUDIT_TABLE as n,appendAuthAuditEntry as m,createAuthAuditReader as l,ensureAuthAuditTable as p,readAuthAuditLog as d}from"./audit.mjs";import{authAuditHook as E,buildAuditEntry as f,eventForPath as T,withAuthAudit as S}from"./packem_shared/authAuditHook-DPTKdjBe.mjs";import{READ_AUDIT_PATH as _,INTERNAL_SECRET_HEADER as D,RESOLVE_SESSION_PATH as c,LunoraAuthDO as H}from"./packem_shared/AUTH_DO_AUDIT_PATH-u9QgGb_v.mjs";import{createAuth as U,resolveAuthOptions as R}from"./packem_shared/createAuth-8aUw8v8D.mjs";import{authDoColumnAdditions as v,authDoSchemaStatements as L}from"./packem_shared/authDoColumnAdditions-UwF3Rl41.mjs";import{createDoAuthWiring as O}from"./packem_shared/createDoAuthWiring-BekpJYhd.mjs";import{emailGateDatabaseHooks as N,withEmailGate as w}from"./packem_shared/emailGateDatabaseHooks-CAygR3iq.mjs";import{assertEmailAllowed as M,classifyEmail as C,emailGateMiddleware as k,loadEmailDomainLists as q}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-DHZL9fNl.mjs";import{legacyIssuerCleanupStatements as K}from"./packem_shared/legacyIssuerCleanupStatements-D9Kf8OD1.mjs";import{LunoraAuthHeadersError as X,withAuthPlugins as Z}from"./middleware.mjs";import{compileMigrationsSql as tt,ensureMigrated as et}from"./packem_shared/compileMigrationsSql-DKGrw7Lf.mjs";import{default as ot}from"./schema.mjs";import{sessionPresets as it,validateSessionPolicy as At}from"./packem_shared/sessionPresets-C867Mlo4.mjs";import{c as st,d as nt}from"./packem_shared/sql-store-CYa4HJsO.mjs";import{createMemoryAuthStore as lt,matchesWhere as pt}from"./store.mjs";import{TURNSTILE_VERIFY_ENDPOINT as ht,verifyTurnstile as Et}from"./turnstile.mjs";import{verifyTurnstileMiddleware as Tt}from"./turnstile-middleware.mjs";export{n as AUTH_AUDIT_TABLE,_ as AUTH_DO_AUDIT_PATH,D as AUTH_DO_SECRET_HEADER,c as AUTH_DO_SESSION_PATH,G as DEFAULT_AUTH_BASE_PATH,A as LunoraAuthAdminError,H as LunoraAuthDO,X as LunoraAuthHeadersError,ht as TURNSTILE_VERIFY_ENDPOINT,m as appendAuthAuditEntry,M as assertEmailAllowed,E as authAuditHook,v as authDoColumnAdditions,L as authDoSchemaStatements,ot as authTables,f as buildAuditEntry,C as classifyEmail,tt as compileMigrationsSql,U as createAuth,u as createAuthAdmin,l as createAuthAuditReader,O as createDoAuthWiring,lt as createMemoryAuthStore,W as createSignUpInvitation,st as createSqlAuthStore,nt as d1Executor,N as emailGateDatabaseHooks,k as emailGateMiddleware,p as ensureAuthAuditTable,et as ensureMigrated,T as eventForPath,B as handleAuthRequest,K as legacyIssuerCleanupStatements,Y as listSignUpInvitations,q as loadEmailDomainLists,r as lunoraAuthAdapter,o as lunoraD1Adapter,a as lunoraDoAdapter,pt as matchesWhere,j as pruneSignUpInvitations,d as readAuthAuditLog,R as resolveAuthOptions,z as revokeSignUpInvitation,it as sessionPresets,At as validateSessionPolicy,Et as verifyTurnstile,Tt as verifyTurnstileMiddleware,S as withAuthAudit,Z as withAuthPlugins,w as withEmailGate};
1
+ import{l as r,a as o,b as a}from"./packem_shared/adapter-CG0Yv85f.mjs";import{LunoraAuthAdminError as A,createAuthAdmin as u}from"./packem_shared/LunoraAuthAdminError-uhKG1MgQ.mjs";import{AUTH_AUDIT_TABLE as n,appendAuthAuditEntry as m,createAuthAuditReader as l,ensureAuthAuditTable as p,readAuthAuditLog as d}from"./audit.mjs";import{authAuditHook as E,buildAuditEntry as f,eventForPath as T,withAuthAudit as S}from"./packem_shared/authAuditHook-DPTKdjBe.mjs";import{READ_AUDIT_PATH as _,INTERNAL_SECRET_HEADER as D,RESOLVE_SESSION_PATH as c,LunoraAuthDO as H}from"./packem_shared/AUTH_DO_AUDIT_PATH-u9QgGb_v.mjs";import{createAuth as U,resolveAuthOptions as R}from"./packem_shared/createAuth-8aUw8v8D.mjs";import{authDoColumnAdditions as v,authDoSchemaStatements as L}from"./packem_shared/authDoColumnAdditions-UwF3Rl41.mjs";import{createDoAuthWiring as O}from"./packem_shared/createDoAuthWiring-zfQiAS75.mjs";import{emailGateDatabaseHooks as N,withEmailGate as w}from"./packem_shared/emailGateDatabaseHooks-CAygR3iq.mjs";import{assertEmailAllowed as M,classifyEmail as C,emailGateMiddleware as k,loadEmailDomainLists as q}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-DHZL9fNl.mjs";import{legacyIssuerCleanupStatements as K}from"./packem_shared/legacyIssuerCleanupStatements-D9Kf8OD1.mjs";import{LunoraAuthHeadersError as X,withAuthPlugins as Z}from"./middleware.mjs";import{compileMigrationsSql as tt,ensureMigrated as et}from"./packem_shared/compileMigrationsSql-DKGrw7Lf.mjs";import{default as ot}from"./schema.mjs";import{sessionPresets as it,validateSessionPolicy as At}from"./packem_shared/sessionPresets-C867Mlo4.mjs";import{c as st,d as nt}from"./packem_shared/sql-store-CYa4HJsO.mjs";import{createMemoryAuthStore as lt,matchesWhere as pt}from"./store.mjs";import{TURNSTILE_VERIFY_ENDPOINT as ht,verifyTurnstile as Et}from"./turnstile.mjs";import{verifyTurnstileMiddleware as Tt}from"./turnstile-middleware.mjs";export{n as AUTH_AUDIT_TABLE,_ as AUTH_DO_AUDIT_PATH,D as AUTH_DO_SECRET_HEADER,c as AUTH_DO_SESSION_PATH,G as DEFAULT_AUTH_BASE_PATH,A as LunoraAuthAdminError,H as LunoraAuthDO,X as LunoraAuthHeadersError,ht as TURNSTILE_VERIFY_ENDPOINT,m as appendAuthAuditEntry,M as assertEmailAllowed,E as authAuditHook,v as authDoColumnAdditions,L as authDoSchemaStatements,ot as authTables,f as buildAuditEntry,C as classifyEmail,tt as compileMigrationsSql,U as createAuth,u as createAuthAdmin,l as createAuthAuditReader,O as createDoAuthWiring,lt as createMemoryAuthStore,W as createSignUpInvitation,st as createSqlAuthStore,nt as d1Executor,N as emailGateDatabaseHooks,k as emailGateMiddleware,p as ensureAuthAuditTable,et as ensureMigrated,T as eventForPath,B as handleAuthRequest,K as legacyIssuerCleanupStatements,Y as listSignUpInvitations,q as loadEmailDomainLists,r as lunoraAuthAdapter,o as lunoraD1Adapter,a as lunoraDoAdapter,pt as matchesWhere,j as pruneSignUpInvitations,d as readAuthAuditLog,R as resolveAuthOptions,z as revokeSignUpInvitation,it as sessionPresets,At as validateSessionPolicy,Et as verifyTurnstile,Tt as verifyTurnstileMiddleware,S as withAuthAudit,Z as withAuthPlugins,w as withEmailGate};
@@ -0,0 +1 @@
1
+ import{INTERNAL_SECRET_HEADER as d,RESOLVE_SESSION_PATH as f,READ_AUDIT_PATH as m}from"./AUTH_DO_AUDIT_PATH-u9QgGb_v.mjs";import{isAuthRoutePath as h,DEFAULT_AUTH_BASE_PATH as y}from"./DEFAULT_AUTH_BASE_PATH-DneiLGpv.mjs";const E=c=>{const{internalSecret:s,jurisdiction:a,objectName:l="auth"}=c;let{namespace:r}=c;if(r&&a!==void 0){if(typeof r.jurisdiction!="function")throw new TypeError(`@lunora/auth: Durable Object namespace does not support jurisdiction("${a}") — update @cloudflare/workers-types or remove the jurisdiction option`);r=r.jurisdiction(a)}const u=()=>{if(r)return r.get(r.idFromName(l))},p=async(t,n,o)=>{if(!s)return;const i=u();if(!i)return;const e=await i.fetch(new Request(new URL(t,n),{body:JSON.stringify(o),headers:{"content-type":"application/json",[d]:s},method:"POST"}));return e.ok?e:void 0};return{auditReader:{read:async t=>{const n=await p(m,"https://auth-do.invalid",t);return n?(await n.json())?.entries??[]:[]}},authHandler:async t=>{if(h(new URL(t.url).pathname,y))return u()?.fetch(t)},resolveIdentity:async t=>{if(!s)return null;const n=u();if(!n)return null;const o=new Headers(t.headers);o.set(d,s);const i=await n.fetch(new Request(new URL(f,t.url),{headers:o}));if(!i.ok)return null;const e=await i.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{E as createDoAuthWiring};
@@ -0,0 +1 @@
1
+ import{oauthProviderClient as m}from"@better-auth/oauth-provider/client";import{passkeyClient as h}from"@better-auth/passkey/client";import{oneTapClient as g,lastLoginMethodClient as d,deviceAuthorizationClient as p,anonymousClient as C,multiSessionClient as y,phoneNumberClient as f,usernameClient as S,adminClient as T,emailOTPClient as L,magicLinkClient as b,twoFactorClient as P,organizationClient as k}from"better-auth/client/plugins";const i=Symbol.for("lunora:session-change-listeners"),v=()=>{const n=globalThis;let o=n[i];return o===void 0&&(o=new Set,n[i]=o),o},r=async()=>{const n=[];for(const o of v())try{n.push(o())}catch{}await Promise.allSettled(n)},s={organization:k,twoFactor:P,passkey:h,magicLink:b,emailOtp:L,admin:T,username:S,phoneNumber:f,multiSession:y,anonymous:C,deviceAuthorization:p,lastLoginMethod:d,oauthProvider:m},A=(n={})=>{const o=[];for(const e of Object.keys(s))n[e]&&o.push(s[e]());return o},E=()=>globalThis.location?.origin,z=async()=>r(),I=()=>({fetchPlugins:[{hooks:{onSuccess:n=>{(n.request.method??"GET").toUpperCase()!=="GET"&&r().catch(()=>{})}},id:"lunora-session-sync",name:"lunora-session-sync"}],id:"lunora-session-sync"}),G=(n,o={})=>{const{baseURL:e,extraPlugins:a=[],oneTapClientId:t,plugins:l,...c}=o,u=t===void 0||t===""?[]:[g({clientId:t})];return n({...c,baseURL:e??E(),plugins:[I(),...A(l),...u,...a]})};export{G as createLunoraAuthClient,A as lunoraAuthPlugins,I as lunoraSessionSync,z as notifyLunoraSessionChange};
@@ -46,6 +46,55 @@ interface CreateLunoraAuthClientOptions {
46
46
  /** Which standard client plugins to include. */
47
47
  plugins?: LunoraAuthPluginToggles;
48
48
  }
49
+ /**
50
+ * What {@link lunoraSessionSync} returns: a better-auth client plugin, typed
51
+ * narrowly rather than as `BetterAuthClientPlugin` — widening a plugin to that
52
+ * type collapses better-auth's session inference on the client it joins.
53
+ */
54
+ interface LunoraSessionSyncPlugin {
55
+ fetchPlugins: {
56
+ hooks: {
57
+ onSuccess: (context: {
58
+ request: {
59
+ method?: string;
60
+ };
61
+ }) => void;
62
+ };
63
+ id: string;
64
+ name: string;
65
+ }[];
66
+ id: "lunora-session-sync";
67
+ }
68
+ /**
69
+ * Tell every `LunoraClient` in the page that the auth session may have changed,
70
+ * so each asks `/get-session` who is signed in now.
71
+ *
72
+ * Needed for a **cookie** session: a sign-in or sign-out sets or clears an
73
+ * `HttpOnly` cookie in a request the Lunora client never sees, and nothing it
74
+ * can observe changes. Until it re-resolves, its live queries keep showing the
75
+ * previous user's rows over a socket still authenticated as them.
76
+ * {@link lunoraSessionSync} (installed by {@link createLunoraAuthClient}) and
77
+ * `@lunora/auth-ui` call it for you; call it yourself after a session change
78
+ * made any other way.
79
+ *
80
+ * Resolves once every client has re-resolved (or failed to), so code that
81
+ * reads `client.currentIdentity()` next can `await` it. Never rejects.
82
+ */
83
+ declare const notifyLunoraSessionChange: () => Promise<void>;
84
+ /**
85
+ * A better-auth client plugin that, after every successful auth request that
86
+ * can change the session (anything but a `GET` — sign-in, sign-up, sign-out,
87
+ * 2FA, account switch, session revocation), calls
88
+ * {@link notifyLunoraSessionChange}.
89
+ *
90
+ * {@link createLunoraAuthClient} always installs it. Add it yourself when you
91
+ * call `createAuthClient` directly:
92
+ *
93
+ * ```ts
94
+ * export const authClient = createAuthClient({ plugins: [lunoraSessionSync()] });
95
+ * ```
96
+ */
97
+ declare const lunoraSessionSync: () => LunoraSessionSyncPlugin;
49
98
  /**
50
99
  * Build a better-auth client with Lunora's standard plugin set from toggles.
51
100
  *
@@ -163,4 +212,36 @@ type LunoraAuthClientPlugin,
163
212
  * to `createAuth`: a server plugin without its client counterpart leaves
164
213
  * those actions untyped/unavailable, and vice-versa.
165
214
  */
166
- type LunoraAuthPluginToggles, createLunoraAuthClient, lunoraAuthPlugins };
215
+ type LunoraAuthPluginToggles,
216
+ /**
217
+ * Client-side counterparts to the server plugins re-exported from
218
+ * `@lunora/auth/plugins`, surfaced under `@lunora/auth/plugins/client`.
219
+ *
220
+ * better-auth plugins come in two halves: a **server** plugin you pass to
221
+ * `betterAuth()` (re-exported from `@lunora/auth/plugins`) and a **client**
222
+ * plugin you pass to `createAuthClient()`. Both halves must be registered for a
223
+ * plugin's endpoints, inferred types, and client actions (e.g.
224
+ * `authClient.twoFactor.*`, `authClient.organization.*`, the `twoFactorRedirect`
225
+ * sign-in flow) to exist. This module is the client half so consumers don't have
226
+ * to reach into better-auth's `better-auth/client/plugins` subpath directly.
227
+ *
228
+ * # Wiring
229
+ *
230
+ * ```ts
231
+ * import { createAuthClient } from "better-auth/client"; // or a framework adapter
232
+ * import { organizationClient, twoFactorClient } from "@lunora/auth/plugins/client";
233
+ *
234
+ * export const authClient = createAuthClient({
235
+ * baseURL: import.meta.env.VITE_AUTH_URL,
236
+ * plugins: [
237
+ * organizationClient(),
238
+ * twoFactorClient({ onTwoFactorRedirect: () => location.assign("/2fa") }),
239
+ * ],
240
+ * });
241
+ * ```
242
+ *
243
+ * Keep the client plugin list in parity with the server `plugins` array passed
244
+ * to `createAuth`: a server plugin without its client counterpart leaves
245
+ * those actions untyped/unavailable, and vice-versa.
246
+ */
247
+ type LunoraSessionSyncPlugin, createLunoraAuthClient, lunoraAuthPlugins, lunoraSessionSync, notifyLunoraSessionChange };
@@ -46,6 +46,55 @@ interface CreateLunoraAuthClientOptions {
46
46
  /** Which standard client plugins to include. */
47
47
  plugins?: LunoraAuthPluginToggles;
48
48
  }
49
+ /**
50
+ * What {@link lunoraSessionSync} returns: a better-auth client plugin, typed
51
+ * narrowly rather than as `BetterAuthClientPlugin` — widening a plugin to that
52
+ * type collapses better-auth's session inference on the client it joins.
53
+ */
54
+ interface LunoraSessionSyncPlugin {
55
+ fetchPlugins: {
56
+ hooks: {
57
+ onSuccess: (context: {
58
+ request: {
59
+ method?: string;
60
+ };
61
+ }) => void;
62
+ };
63
+ id: string;
64
+ name: string;
65
+ }[];
66
+ id: "lunora-session-sync";
67
+ }
68
+ /**
69
+ * Tell every `LunoraClient` in the page that the auth session may have changed,
70
+ * so each asks `/get-session` who is signed in now.
71
+ *
72
+ * Needed for a **cookie** session: a sign-in or sign-out sets or clears an
73
+ * `HttpOnly` cookie in a request the Lunora client never sees, and nothing it
74
+ * can observe changes. Until it re-resolves, its live queries keep showing the
75
+ * previous user's rows over a socket still authenticated as them.
76
+ * {@link lunoraSessionSync} (installed by {@link createLunoraAuthClient}) and
77
+ * `@lunora/auth-ui` call it for you; call it yourself after a session change
78
+ * made any other way.
79
+ *
80
+ * Resolves once every client has re-resolved (or failed to), so code that
81
+ * reads `client.currentIdentity()` next can `await` it. Never rejects.
82
+ */
83
+ declare const notifyLunoraSessionChange: () => Promise<void>;
84
+ /**
85
+ * A better-auth client plugin that, after every successful auth request that
86
+ * can change the session (anything but a `GET` — sign-in, sign-up, sign-out,
87
+ * 2FA, account switch, session revocation), calls
88
+ * {@link notifyLunoraSessionChange}.
89
+ *
90
+ * {@link createLunoraAuthClient} always installs it. Add it yourself when you
91
+ * call `createAuthClient` directly:
92
+ *
93
+ * ```ts
94
+ * export const authClient = createAuthClient({ plugins: [lunoraSessionSync()] });
95
+ * ```
96
+ */
97
+ declare const lunoraSessionSync: () => LunoraSessionSyncPlugin;
49
98
  /**
50
99
  * Build a better-auth client with Lunora's standard plugin set from toggles.
51
100
  *
@@ -163,4 +212,36 @@ type LunoraAuthClientPlugin,
163
212
  * to `createAuth`: a server plugin without its client counterpart leaves
164
213
  * those actions untyped/unavailable, and vice-versa.
165
214
  */
166
- type LunoraAuthPluginToggles, createLunoraAuthClient, lunoraAuthPlugins };
215
+ type LunoraAuthPluginToggles,
216
+ /**
217
+ * Client-side counterparts to the server plugins re-exported from
218
+ * `@lunora/auth/plugins`, surfaced under `@lunora/auth/plugins/client`.
219
+ *
220
+ * better-auth plugins come in two halves: a **server** plugin you pass to
221
+ * `betterAuth()` (re-exported from `@lunora/auth/plugins`) and a **client**
222
+ * plugin you pass to `createAuthClient()`. Both halves must be registered for a
223
+ * plugin's endpoints, inferred types, and client actions (e.g.
224
+ * `authClient.twoFactor.*`, `authClient.organization.*`, the `twoFactorRedirect`
225
+ * sign-in flow) to exist. This module is the client half so consumers don't have
226
+ * to reach into better-auth's `better-auth/client/plugins` subpath directly.
227
+ *
228
+ * # Wiring
229
+ *
230
+ * ```ts
231
+ * import { createAuthClient } from "better-auth/client"; // or a framework adapter
232
+ * import { organizationClient, twoFactorClient } from "@lunora/auth/plugins/client";
233
+ *
234
+ * export const authClient = createAuthClient({
235
+ * baseURL: import.meta.env.VITE_AUTH_URL,
236
+ * plugins: [
237
+ * organizationClient(),
238
+ * twoFactorClient({ onTwoFactorRedirect: () => location.assign("/2fa") }),
239
+ * ],
240
+ * });
241
+ * ```
242
+ *
243
+ * Keep the client plugin list in parity with the server `plugins` array passed
244
+ * to `createAuth`: a server plugin without its client counterpart leaves
245
+ * those actions untyped/unavailable, and vice-versa.
246
+ */
247
+ type LunoraSessionSyncPlugin, createLunoraAuthClient, lunoraAuthPlugins, lunoraSessionSync, notifyLunoraSessionChange };
@@ -1 +1 @@
1
- import{createLunoraAuthClient as t,lunoraAuthPlugins as n}from"./packem_shared/createLunoraAuthClient-DhjhCwmM.mjs";import{apiKeyClient as l}from"@better-auth/api-key/client";import{oauthDeviceAuthorizationClient as a,oauthProviderClient as C}from"@better-auth/oauth-provider/client";import{passkeyClient as s}from"@better-auth/passkey/client";import{adminClient as d,anonymousClient as p,customSessionClient as h,deviceAuthorizationClient as f,emailOTPClient as c,inferAdditionalFields as A,inferOrgAdditionalFields as g,jwtClient as x,lastLoginMethodClient as T,magicLinkClient as k,multiSessionClient as v,oneTapClient as w,oneTimeTokenClient as y,organizationClient as z,phoneNumberClient as F,siweClient as L,twoFactorClient as P,usernameClient as O}from"better-auth/client/plugins";export{d as adminClient,p as anonymousClient,l as apiKeyClient,t as createLunoraAuthClient,h as customSessionClient,f as deviceAuthorizationClient,c as emailOTPClient,A as inferAdditionalFields,g as inferOrgAdditionalFields,x as jwtClient,T as lastLoginMethodClient,n as lunoraAuthPlugins,k as magicLinkClient,v as multiSessionClient,a as oauthDeviceAuthorizationClient,C as oauthProviderClient,w as oneTapClient,y as oneTimeTokenClient,z as organizationClient,s as passkeyClient,F as phoneNumberClient,L as siweClient,P as twoFactorClient,O as usernameClient};
1
+ import{createLunoraAuthClient as n,lunoraAuthPlugins as t,lunoraSessionSync as o,notifyLunoraSessionChange as l}from"./packem_shared/createLunoraAuthClient-DZwrWj-w.mjs";import{apiKeyClient as a}from"@better-auth/api-key/client";import{oauthDeviceAuthorizationClient as s,oauthProviderClient as u}from"@better-auth/oauth-provider/client";import{passkeyClient as d}from"@better-auth/passkey/client";import{adminClient as p,anonymousClient as f,customSessionClient as c,deviceAuthorizationClient as g,emailOTPClient as A,inferAdditionalFields as x,inferOrgAdditionalFields as y,jwtClient as S,lastLoginMethodClient as L,magicLinkClient as T,multiSessionClient as k,oneTapClient as v,oneTimeTokenClient as w,organizationClient as z,phoneNumberClient as F,siweClient as P,twoFactorClient as O,usernameClient as b}from"better-auth/client/plugins";export{p as adminClient,f as anonymousClient,a as apiKeyClient,n as createLunoraAuthClient,c as customSessionClient,g as deviceAuthorizationClient,A as emailOTPClient,x as inferAdditionalFields,y as inferOrgAdditionalFields,S as jwtClient,L as lastLoginMethodClient,t as lunoraAuthPlugins,o as lunoraSessionSync,T as magicLinkClient,k as multiSessionClient,l as notifyLunoraSessionChange,s as oauthDeviceAuthorizationClient,u as oauthProviderClient,v as oneTapClient,w as oneTimeTokenClient,z as organizationClient,d as passkeyClient,F as phoneNumberClient,P as siweClient,O as twoFactorClient,b as usernameClient};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/auth",
3
- "version": "1.0.0-alpha.162",
3
+ "version": "1.0.0-alpha.164",
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.3",
104
104
  "@better-auth/passkey": "1.7.3",
105
105
  "@better-auth/scim": "1.7.3",
106
- "@lunora/errors": "1.0.0-alpha.41",
107
- "@lunora/values": "1.0.0-alpha.52",
106
+ "@lunora/errors": "1.0.0-alpha.43",
107
+ "@lunora/values": "1.0.0-alpha.54",
108
108
  "@visulima/disposable-email-domains": "1.1.1",
109
109
  "@visulima/email-verifier": "1.0.9",
110
110
  "@visulima/free-email-domains": "1.0.1",
@@ -1 +0,0 @@
1
- import{INTERNAL_SECRET_HEADER as u,RESOLVE_SESSION_PATH as m,READ_AUDIT_PATH as p}from"./AUTH_DO_AUDIT_PATH-u9QgGb_v.mjs";import{isAuthRoutePath as f,DEFAULT_AUTH_BASE_PATH as h}from"./DEFAULT_AUTH_BASE_PATH-DneiLGpv.mjs";const R=l=>{const{internalSecret:o,namespace:a,objectName:c="auth"}=l,i=()=>{if(a)return a.get(a.idFromName(c))},d=async(t,n,r)=>{if(!o)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]:o},method:"POST"}));return e.ok?e:void 0};return{auditReader:{read:async t=>{const n=await d(p,"https://auth-do.invalid",t);return n?(await n.json())?.entries??[]:[]}},authHandler:async t=>{if(f(new URL(t.url).pathname,h))return i()?.fetch(t)},resolveIdentity:async t=>{if(!o)return null;const n=i();if(!n)return null;const r=new Headers(t.headers);r.set(u,o);const s=await n.fetch(new Request(new URL(m,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{R as createDoAuthWiring};
@@ -1 +0,0 @@
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 f,magicLinkClient as k,twoFactorClient as y,organizationClient as P}from"better-auth/client/plugins";const o={organization:P,twoFactor:y,passkey:m,magicLink:k,emailOtp:f,admin:b,username:L,phoneNumber:d,multiSession:h,anonymous:g,deviceAuthorization:p,lastLoginMethod:C,oauthProvider:u},T=(t={})=>{const n=[];for(const i of Object.keys(o))t[i]&&n.push(o[i]());return n},v=()=>globalThis.location?.origin,I=(t,n={})=>{const{baseURL:i,extraPlugins:a=[],oneTapClientId:e,plugins:r,...s}=n,l=e===void 0||e===""?[]:[c({clientId:e})];return t({...s,baseURL:i??v(),plugins:[...T(r),...l,...a]})};export{I as createLunoraAuthClient,T as lunoraAuthPlugins};