@lunora/auth 1.0.0-alpha.263 → 1.0.0-alpha.264

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.d.mts CHANGED
@@ -8,7 +8,7 @@ declare const AUTH_AUDIT_TABLE = "__lunora_auth_audit__";
8
8
  * plugins can record their own events without a union change — the union just
9
9
  * gives autocomplete for the common ones.
10
10
  */
11
- type AuthAuditEvent = "account-link" | "account-unlink" | "email-verification" | "mfa-disable" | "mfa-enable" | "password-change" | "password-reset" | "session-revoke" | "sign-in" | "sign-in-initiated" | "sign-out" | "sign-up" | "token-refresh" | (string & {});
11
+ type AuthAuditEvent = "account-link" | "account-unlink" | "admin-impersonate-start" | "admin-impersonate-stop" | "admin-password-set" | "admin-role-change" | "admin-session-revoke" | "admin-user-ban" | "admin-user-create" | "admin-user-remove" | "admin-user-unban" | "admin-user-update" | "api-key-create" | "api-key-delete" | "api-key-update" | "device-approve" | "device-deny" | "email-change" | "email-change-request" | "email-verification" | "mfa-backup-codes-regenerate" | "mfa-disable" | "mfa-enable" | "one-time-token-create" | "passkey-add" | "passkey-remove" | "passkey-rename" | "password-change" | "password-reset" | "password-reset-request" | "phone-verification" | "session-revoke" | "session-switch" | "sign-in" | "sign-in-initiated" | "sign-out" | "sign-up" | "sso-provider-delete" | "sso-provider-register" | "sso-provider-update" | "token-refresh" | "user-delete" | "user-delete-request" | (string & {});
12
12
  /** Whether the recorded operation succeeded or failed (e.g. a rejected sign-in). */
13
13
  type AuthAuditOutcome = "failure" | "success";
14
14
  /** One recorded auth/security event, in monotonic `seq` order. */
@@ -59,6 +59,11 @@ interface AppendAuthAuditEntry {
59
59
  }
60
60
  /** Options for {@link appendAuthAuditEntry}. */
61
61
  interface AppendAuthAuditOptions {
62
+ /**
63
+ * The key a failed attempt's identifiers are HMAC'd under. A failed attempt can carry text the caller typed into an
64
+ * identifier field, such as a pasted password, and an unkeyed digest of that would be brute-forceable.
65
+ */
66
+ hashKey?: string;
62
67
  /**
63
68
  * Redact secrets/PII in the `detail` payload before persisting. Defaults to
64
69
  * `true`. Set `false` only for a trusted, pre-scrubbed payload.
package/dist/audit.d.ts CHANGED
@@ -8,7 +8,7 @@ declare const AUTH_AUDIT_TABLE = "__lunora_auth_audit__";
8
8
  * plugins can record their own events without a union change — the union just
9
9
  * gives autocomplete for the common ones.
10
10
  */
11
- type AuthAuditEvent = "account-link" | "account-unlink" | "email-verification" | "mfa-disable" | "mfa-enable" | "password-change" | "password-reset" | "session-revoke" | "sign-in" | "sign-in-initiated" | "sign-out" | "sign-up" | "token-refresh" | (string & {});
11
+ type AuthAuditEvent = "account-link" | "account-unlink" | "admin-impersonate-start" | "admin-impersonate-stop" | "admin-password-set" | "admin-role-change" | "admin-session-revoke" | "admin-user-ban" | "admin-user-create" | "admin-user-remove" | "admin-user-unban" | "admin-user-update" | "api-key-create" | "api-key-delete" | "api-key-update" | "device-approve" | "device-deny" | "email-change" | "email-change-request" | "email-verification" | "mfa-backup-codes-regenerate" | "mfa-disable" | "mfa-enable" | "one-time-token-create" | "passkey-add" | "passkey-remove" | "passkey-rename" | "password-change" | "password-reset" | "password-reset-request" | "phone-verification" | "session-revoke" | "session-switch" | "sign-in" | "sign-in-initiated" | "sign-out" | "sign-up" | "sso-provider-delete" | "sso-provider-register" | "sso-provider-update" | "token-refresh" | "user-delete" | "user-delete-request" | (string & {});
12
12
  /** Whether the recorded operation succeeded or failed (e.g. a rejected sign-in). */
13
13
  type AuthAuditOutcome = "failure" | "success";
14
14
  /** One recorded auth/security event, in monotonic `seq` order. */
@@ -59,6 +59,11 @@ interface AppendAuthAuditEntry {
59
59
  }
60
60
  /** Options for {@link appendAuthAuditEntry}. */
61
61
  interface AppendAuthAuditOptions {
62
+ /**
63
+ * The key a failed attempt's identifiers are HMAC'd under. A failed attempt can carry text the caller typed into an
64
+ * identifier field, such as a pasted password, and an unkeyed digest of that would be brute-forceable.
65
+ */
66
+ hashKey?: string;
62
67
  /**
63
68
  * Redact secrets/PII in the `detail` payload before persisting. Defaults to
64
69
  * `true`. Set `false` only for a trusted, pre-scrubbed payload.
package/dist/audit.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import{standardRules as N,piiRules as D,redact as $}from"@visulima/redact";const C=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"]),x=new Set(["card","pass","pin","session"]),U=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"]),z=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"],F=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"]),G=new Set(["count","counts","length","limit","limits","size","tokens","total","usage"]),X=new Set(["max","min","num","total"]),S=4096,Z=128,j=16384,l="<REDACTED>",P="[redaction budget exceeded]",v=e=>e.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(t=>t.length>0),y=e=>e.length>3&&e.endsWith("s")&&!e.endsWith("ss")?e.slice(0,-1):e,H=(e,t)=>{const n=y(e[t]),s=t>0?y(e[t-1]):void 0;if(C.has(n))return n;if(s!==void 0){if(n==="key"&&U.has(s))return"key";if(n==="code"&&M.has(s))return"code";if(z.has(`${s} ${n}`))return`${s} ${n}`}return W.some(a=>n.endsWith(a))?n:void 0},k=e=>{const t=v(e);if(t.length===0)return"none";const n=G.has(t.at(-1))||X.has(t[0]);for(let s=t.length-1;s>=0;s-=1){const a=H(t,s);if(a!==void 0)return n?"count-secret":t.slice(s+1).every(i=>F.has(i))?x.has(a)&&s===t.length-1?"scalar-secret":"secret":"none"}return"none"},V=e=>typeof e=="boolean"||e===null||e===void 0?e:l,q=e=>{const t=e.indexOf("://")+3,n=e.slice(t),s=n.split(/[?#]/,1)[0],a=s.lastIndexOf("@"),i=s.indexOf(":"),c=s.indexOf("/"),r=i!==-1&&/^\d+$/.test(s.slice(i+1,c===-1?void 0:c)),o=i!==-1&&!r&&(c===-1||i<c);if(a===-1&&o&&n.includes("@",s.length))return e.slice(0,t);const d=a!==-1&&(c===-1||a<c||i!==-1&&i<a&&!r);return`${e.slice(0,t)}${d?s.slice(a+1):s}`},B=/\b[a-z][\d+.a-z-]{1,15}:\/\/[^\s"'<>()[\]{}]+/gi,Y=/-----BEGIN ([A-Z ]{0,32}PRIVATE KEY)-----[\s\S]*?(?:-----END [A-Z ]{0,32}PRIVATE KEY-----|$)/g,K=/\b(Basic|Bearer|Digest)\s+[\w+/=.~-]{4,}/g,R=String.raw`%[\dA-Fa-f]{2}|\\(?:[bfnrt]|u[\dA-Fa-f]{4})`,I=[{body:String.raw`[\dA-Za-z]{10,}`,name:"Stripe secret or restricted key",prefix:String.raw`[rs]k_(?:live|test)_`},{body:String.raw`[\d+/=A-Za-z]{20,}`,name:"Stripe webhook secret",prefix:"whsec_"},{body:String.raw`[\dA-Za-z]{30,}`,name:"GitHub classic token (personal, OAuth, user/server-to-server, refresh)",prefix:"gh[oprsu]_"},{body:String.raw`\w{20,}`,name:"GitHub fine-grained token",prefix:"github_pat_"},{body:String.raw`[\w-]{20,}`,name:"GitLab personal, pipeline-trigger and deploy tokens",prefix:"gl(?:pat|ptt|dt)-"},{body:String.raw`[\dA-Za-z-]{10,}`,name:"Slack token",prefix:"xox[a-eprs]-"},{body:String.raw`\d-[\dA-Za-z-]{10,}`,name:"Slack app-level token",prefix:"xapp-"},{body:String.raw`[\dA-Z]{16}\b`,name:"AWS access-key id, long-lived and temporary",prefix:"(?:AKIA|ASIA)"},{body:String.raw`[\w-]{35}(?![\w-])`,name:"Google API key",prefix:"AIza"},{body:String.raw`[\w-]{24,}`,name:"Google OAuth client secret",prefix:"GOCSPX-"},{body:String.raw`[\w-]{20,}`,name:"Google OAuth access token",prefix:String.raw`ya29\.`},{body:String.raw`[\dA-Za-z]{36}\b`,name:"npm token",prefix:"npm_"},{body:String.raw`[\dA-Za-z]{30,}`,name:"Hugging Face token",prefix:"hf_"},{body:String.raw`[\dA-Fa-f]{32}\b`,name:"Shopify token",prefix:"shp(?:at|ca|pa|ss)_"},{body:String.raw`[\da-f]{64}\b`,name:"DigitalOcean token",prefix:"do[opr]_v1_"},{body:String.raw`[\w-]{20,}`,name:"OpenAI project/service/admin key, Anthropic key",prefix:"sk-(?:admin|ant|proj|svcacct)-"},{body:String.raw`[\dA-Za-z]{20}T3BlbkFJ[\dA-Za-z]{20}\b`,name:"OpenAI legacy key",prefix:"sk-"},{body:String.raw`[\w-]{22}\.[\w-]{43}(?![\w-])`,name:"SendGrid key",prefix:String.raw`SG\.`}],J=String.raw`(?<=^|[^\w-]|${R})eyJ[\w-]{2,}\.[\w-]{2,}\.[\w-]*`,Q=new RegExp([...I.map(({body:e,prefix:t})=>String.raw`(?<=^|[^\dA-Za-z]|${R})${t}${e}`),J].join("|"),"g"),ee=new RegExp([...I.map(({prefix:e})=>e),"eyJ"].join("|")),te=/(\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,w=/(?:basic|bearer|digest|token)\s+[^\s"&'),;\]}]+|\\"(?:[^"\\\n]|\\[^"])*(?:\\")?|"[^\n"]*"?|'[^\n']*'?|[^\s"&'),;\]}]+/iy,b=/(?:[ \t]+(?![A-Za-z_][\w.-]{0,63}[:=])[^\s,;)\]}]+)*/y,ne=e=>{let t="",n=0;f.lastIndex=0;for(let s=f.exec(e);s!==null;s=f.exec(e)){const a=k(s[2]),i=s.index+s[0].length;w.lastIndex=i;const c=a==="none"?null:w.exec(e);if(c===null||a==="count-secret"&&/^["']?[\d.]+["']?$/.test(c[0])){f.lastIndex=Math.max(i,s.index+1);continue}const r=c[0],o=r.startsWith('\\"')?'\\"':r.startsWith('"')||r.startsWith("'")?r[0]:"";let d=i+r.length;o===""&&s[3]===":"&&(b.lastIndex=d,d+=b.exec(e)?.[0].length??0),t+=`${e.slice(n,i)}${o}${l}${r.length>o.length&&r.endsWith(o)?o:""}`,n=d,f.lastIndex=n}return t+e.slice(n)},se=/[:=@]|basic|bearer|digest|-u\b|--/i,re=e=>{const t=ee.test(e);if(!t&&!se.test(e))return e;const n=e.replaceAll(Y,`-----BEGIN $1-----${l}`).replaceAll(B,q).replaceAll(K,`$1 ${l}`);return ne((t?n.replaceAll(Q,l):n).replaceAll(te,`$1$2$3${l}`))},ae=(e,t)=>{if(t.remaining<=0)return P;const n=e.slice(0,S+Z);t.remaining-=n.length;const s=re(n);return s.length>S||e.length>n.length?`${s.slice(0,S)}…[truncated]`:s},ie=e=>e instanceof Error||e instanceof RegExp||e instanceof Map||e instanceof Set||e instanceof WeakMap||e instanceof WeakSet||e instanceof Promise||e instanceof ArrayBuffer||ArrayBuffer.isView(e),g=Symbol("no-json"),oe=e=>{const{toJSON:t}=e;if(typeof t!="function")return g;try{const n=t.call(e);return n===e?g:n}catch{return g}},ce=32,u=(e,t,n,s,a)=>{if(typeof e=="string")return s?l:ae(e,a);if(typeof e!="object"||e===null||!Array.isArray(e)&&ie(e))return e;if(t.has(e)||n>=ce)return l;const i=Array.isArray(e)?g:oe(e);if(i!==g){t.add(e);const r=u(i,t,n+1,s,a);return t.delete(e),r}t.add(e);const c=Array.isArray(e)?e.map(r=>u(r,t,n+1,s,a)):Object.fromEntries(Object.entries(e).map(([r,o])=>{const d=k(r);return d==="secret"||d==="scalar-secret"&&(typeof o!="object"||o===null)?[r,V(o)]:[r,u(o,t,n+1,d==="count-secret"&&(typeof o=="string"||Array.isArray(o)),a)]}));return t.delete(e),c},de=e=>u(e,new WeakSet,0,!1,{remaining:j}),E="__lunora_auth_audit__",le=[...N,...D],pe=1e3,Ae=1e4,A=null,m=e=>{if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="bigint"||typeof e=="boolean")return String(e)},Ee=async e=>{await e.run(`CREATE TABLE IF NOT EXISTS "${E}" (
1
+ import{standardRules as x,piiRules as $,redact as U}from"@visulima/redact";const M=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"]),z=new Set(["card","pass","pin","session"]),j=new Set(["access","api","client","encryption","master","priv","private","secret","signing"]),F=new Set(["2fa","auth","authorization","backup","factor","hotp","mfa","otp","pin","recovery","reset","security","totp","verification","verify"]),H=new Set(["card no","connection string","database url","one time"]),v=["accesskey","apikey","authorization","cookie","credential","mfacode","otpcode","passcode","passphrase","passwd","password","privatekey","secret","secretkey","sessionid","signature","token"],W=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"]),X=new Set(["count","counts","length","limit","limits","size","tokens","total","usage"]),G=new Set(["max","min","num","total"]),m=4096,P=128,Z=16384,l="<REDACTED>",K="[redaction budget exceeded]",V=e=>e.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(t=>t.length>0),y=e=>e.length>3&&e.endsWith("s")&&!e.endsWith("ss")?e.slice(0,-1):e,q=(e,t)=>{const n=y(e[t]),s=t>0?y(e[t-1]):void 0;if(M.has(n))return n;if(s!==void 0){if(n==="key"&&j.has(s))return"key";if(n==="code"&&F.has(s))return"code";if(H.has(`${s} ${n}`))return`${s} ${n}`}return v.some(r=>n.endsWith(r))?n:void 0},R=e=>{const t=V(e);if(t.length===0)return"none";const n=X.has(t.at(-1))||G.has(t[0]);for(let s=t.length-1;s>=0;s-=1){const r=q(t,s);if(r!==void 0)return n?"count-secret":t.slice(s+1).every(i=>W.has(i))?z.has(r)&&s===t.length-1?"scalar-secret":"secret":"none"}return"none"},B=e=>typeof e=="boolean"||e===null||e===void 0?e:l,Y=e=>{const t=e.indexOf("://")+3,n=e.slice(t),s=n.split(/[?#]/,1)[0],r=s.lastIndexOf("@"),i=s.indexOf(":"),o=s.indexOf("/"),a=i!==-1&&/^\d+$/.test(s.slice(i+1,o===-1?void 0:o)),c=i!==-1&&!a&&(o===-1||i<o);if(r===-1&&c&&n.includes("@",s.length))return e.slice(0,t);const d=r!==-1&&(o===-1||r<o||i!==-1&&i<r&&!a);return`${e.slice(0,t)}${d?s.slice(r+1):s}`},J=/\b[a-z][\d+.a-z-]{1,15}:\/\/[^\s"'<>()[\]{}]+/gi,Q=/-----BEGIN ([A-Z ]{0,32}PRIVATE KEY)-----[\s\S]*?(?:-----END [A-Z ]{0,32}PRIVATE KEY-----|$)/g,ee=/\b(Basic|Bearer|Digest)\s+[\w+/=.~-]{4,}/g,k=String.raw`%[\dA-Fa-f]{2}|\\(?:[bfnrt]|u[\dA-Fa-f]{4})`,L=[{body:String.raw`[\dA-Za-z]{10,}`,name:"Stripe secret or restricted key",prefix:String.raw`[rs]k_(?:live|test)_`},{body:String.raw`[\d+/=A-Za-z]{20,}`,name:"Stripe webhook secret",prefix:"whsec_"},{body:String.raw`[\dA-Za-z]{30,}`,name:"GitHub classic token (personal, OAuth, user/server-to-server, refresh)",prefix:"gh[oprsu]_"},{body:String.raw`\w{20,}`,name:"GitHub fine-grained token",prefix:"github_pat_"},{body:String.raw`[\w-]{20,}`,name:"GitLab personal, pipeline-trigger and deploy tokens",prefix:"gl(?:pat|ptt|dt)-"},{body:String.raw`[\dA-Za-z-]{10,}`,name:"Slack token",prefix:"xox[a-eprs]-"},{body:String.raw`\d-[\dA-Za-z-]{10,}`,name:"Slack app-level token",prefix:"xapp-"},{body:String.raw`[\dA-Z]{16}\b`,name:"AWS access-key id, long-lived and temporary",prefix:"(?:AKIA|ASIA)"},{body:String.raw`[\w-]{35}(?![\w-])`,name:"Google API key",prefix:"AIza"},{body:String.raw`[\w-]{24,}`,name:"Google OAuth client secret",prefix:"GOCSPX-"},{body:String.raw`[\w-]{20,}`,name:"Google OAuth access token",prefix:String.raw`ya29\.`},{body:String.raw`[\dA-Za-z]{36}\b`,name:"npm token",prefix:"npm_"},{body:String.raw`[\dA-Za-z]{30,}`,name:"Hugging Face token",prefix:"hf_"},{body:String.raw`[\dA-Fa-f]{32}\b`,name:"Shopify token",prefix:"shp(?:at|ca|pa|ss)_"},{body:String.raw`[\da-f]{64}\b`,name:"DigitalOcean token",prefix:"do[opr]_v1_"},{body:String.raw`[\w-]{20,}`,name:"OpenAI project/service/admin key, Anthropic key",prefix:"sk-(?:admin|ant|proj|svcacct)-"},{body:String.raw`[\dA-Za-z]{20}T3BlbkFJ[\dA-Za-z]{20}\b`,name:"OpenAI legacy key",prefix:"sk-"},{body:String.raw`[\w-]{22}\.[\w-]{43}(?![\w-])`,name:"SendGrid key",prefix:String.raw`SG\.`}],te=String.raw`(?<=^|[^\w-]|${k})eyJ[\w-]{2,}\.[\w-]{2,}\.[\w-]*`,ne=new RegExp([...L.map(({body:e,prefix:t})=>String.raw`(?<=^|[^\dA-Za-z]|${k})${t}${e}`),te].join("|"),"g"),se=new RegExp([...L.map(({prefix:e})=>e),"eyJ"].join("|")),re=/(\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,w=/(?:basic|bearer|digest|token)\s+[^\s"&'),;\]}]+|\\"(?:[^"\\\n]|\\[^"])*(?:\\")?|"[^\n"]*"?|'[^\n']*'?|[^\s"&'),;\]}]+/iy,I=/(?:[ \t]+(?![A-Za-z_][\w.-]{0,63}[:=])[^\s,;)\]}]+)*/y,ie=e=>{let t="",n=0;f.lastIndex=0;for(let s=f.exec(e);s!==null;s=f.exec(e)){const r=R(s[2]),i=s.index+s[0].length;w.lastIndex=i;const o=r==="none"?null:w.exec(e);if(o===null||r==="count-secret"&&/^["']?[\d.]+["']?$/.test(o[0])){f.lastIndex=Math.max(i,s.index+1);continue}const a=o[0],c=a.startsWith('\\"')?'\\"':a.startsWith('"')||a.startsWith("'")?a[0]:"";let d=i+a.length;c===""&&s[3]===":"&&(I.lastIndex=d,d+=I.exec(e)?.[0].length??0),t+=`${e.slice(n,i)}${c}${l}${a.length>c.length&&a.endsWith(c)?c:""}`,n=d,f.lastIndex=n}return t+e.slice(n)},ae=/[:=@]|basic|bearer|digest|-u\b|--/i,oe=e=>{const t=se.test(e);if(!t&&!ae.test(e))return e;const n=e.replaceAll(Q,`-----BEGIN $1-----${l}`).replaceAll(J,Y).replaceAll(ee,`$1 ${l}`);return ie((t?n.replaceAll(ne,l):n).replaceAll(re,`$1$2$3${l}`))},ce=(e,t)=>{if(t.remaining<=0)return K;const n=e.slice(0,m+P);t.remaining-=n.length;const s=oe(n);return s.length>m||e.length>n.length?`${s.slice(0,m)}…[truncated]`:s},de=e=>e instanceof Error||e instanceof RegExp||e instanceof Map||e instanceof Set||e instanceof WeakMap||e instanceof WeakSet||e instanceof Promise||e instanceof ArrayBuffer||ArrayBuffer.isView(e),u=Symbol("no-json"),le=e=>{const{toJSON:t}=e;if(typeof t!="function")return u;try{const n=t.call(e);return n===e?u:n}catch{return u}},Ee=32,g=(e,t,n,s,r)=>{if(typeof e=="string")return s?l:ce(e,r);if(typeof e!="object"||e===null||!Array.isArray(e)&&de(e))return e;if(t.has(e)||n>=Ee)return l;const i=Array.isArray(e)?u:le(e);if(i!==u){t.add(e);const a=g(i,t,n+1,s,r);return t.delete(e),a}t.add(e);const o=Array.isArray(e)?e.map(a=>g(a,t,n+1,s,r)):Object.fromEntries(Object.entries(e).map(([a,c])=>{const d=R(a);return d==="secret"||d==="scalar-secret"&&(typeof c!="object"||c===null)?[a,B(c)]:[a,g(c,t,n+1,d==="count-secret"&&(typeof c=="string"||Array.isArray(c)),r)]}));return t.delete(e),o},pe=e=>g(e,new WeakSet,0,!1,{remaining:Z}),Ae=(e,t)=>{if(e.size<t)return;const n=e.keys().next().value;n!==void 0&&e.delete(n)},fe=(e,t,n,s)=>{const r=e.get(t);if(r!==void 0)return r;Ae(e,s);const i=n().catch(o=>{throw e.get(t)===i&&e.delete(t),o});return e.set(t,i),i},ue=new TextEncoder,ge=64,me=new Map,b=async e=>fe(me,e,async()=>crypto.subtle.importKey("raw",ue.encode(e),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),ge),A="__lunora_auth_audit__",Se=[...x,...$],N=new Set(["clientId","consentId","invitationId","keyId","memberId","organizationId","providerId","resourceIdentifier","role","roleId","roleName","scimGroupId","scimUserId","targetUserId","teamId"]),_e=/^[^\s?#=@]{1,256}$/u,he="hmac-sha256:",Te="lunora/auth-audit/failed-identifier",O=e=>[...new Uint8Array(e)].map(t=>t.toString(16).padStart(2,"0")).join(""),ye=async(e,t)=>{if(t===void 0)return e;const n=await b(t),s=await b(O(await crypto.subtle.sign("HMAC",n,new TextEncoder().encode(Te)))),r=await Promise.all(Object.entries(e).filter(([i,o])=>N.has(i)&&typeof o=="string").map(async([i,o])=>{const a=await crypto.subtle.sign("HMAC",s,new TextEncoder().encode(String(o)));return[i,he+O(a)]}));return{...e,...Object.fromEntries(r)}},we=e=>{const t=Object.fromEntries(Object.entries(e).filter(([r,i])=>N.has(r)&&typeof i=="string"&&_e.test(i))),n=new Set(Object.keys(t)),s=Object.fromEntries(Object.entries(e).filter(([r])=>!n.has(r)));return{...U(pe(s),Se),...t}},Ie=1e3,be=1e4,p=null,S=e=>{if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="bigint"||typeof e=="boolean")return String(e)},Oe=async e=>{await e.run(`CREATE TABLE IF NOT EXISTS "${A}" (
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 N,piiRules as D,redact as $}from"@visulima/redact";const
9
9
  ip TEXT,
10
10
  user_agent TEXT,
11
11
  detail TEXT
12
- )`,[]);try{await e.run(`ALTER TABLE "${E}" ADD COLUMN target_email TEXT`,[])}catch(t){if(!(t instanceof Error?t.message.toLowerCase():String(t).toLowerCase()).includes("duplicate column"))throw t}},_=new WeakMap,L=e=>{const t=_.get(e);if(t)return t;const n=Ee(e);return _.set(e,n),n.catch(()=>_.delete(e)),n},ue=async(e,t,n={})=>{await L(e);let s;return t.detail!==void 0&&(s=n.redactDetail===!1?t.detail:$(de(t.detail),le)),await e.run(`INSERT INTO "${E}" (ts, event, outcome, actor_id, actor_email, target_email, ip, user_agent, detail) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[t.ts,t.event,t.outcome,t.actorId??A,t.actorEmail??A,t.targetEmail??A,t.ip??A,t.userAgent??A,s===void 0?A:JSON.stringify(s)]),typeof n.retention=="number"&&n.retention>0&&await e.run(`DELETE FROM "${E}" WHERE seq <= (SELECT MAX(seq) - ? FROM "${E}")`,[n.retention]),{...t,detail:s}},fe=async(e,t={})=>{await L(e);const n=Number.isFinite(t.limit)?Math.max(1,Math.min(t.limit,Ae)):pe,s=["seq > ?"],a=[t.sinceSeq??0],i=t.sinceSeq===void 0?"DESC":"ASC";return t.actorId!==void 0&&(s.push("actor_id = ?"),a.push(t.actorId)),t.event!==void 0&&(s.push("event = ?"),a.push(t.event)),a.push(n),(await e.all(`SELECT seq, ts, event, outcome, actor_id, actor_email, target_email, ip, user_agent, detail FROM "${E}" WHERE ${s.join(" AND ")} ORDER BY seq ${i} LIMIT ?`,a)).map(r=>{const o={event:m(r.event)??"",outcome:r.outcome==="failure"?"failure":"success",seq:Number(r.seq),ts:Number(r.ts)},d=[["actorId","actor_id"],["actorEmail","actor_email"],["targetEmail","target_email"],["ip","ip"],["userAgent","user_agent"]];for(const[p,O]of d){const T=m(r[O]);T!==void 0&&(o[p]=T)}const h=m(r.detail);if(h!==void 0)try{const p=JSON.parse(h);typeof p=="object"&&p!==null&&!Array.isArray(p)&&(o.detail=p)}catch{}return o})},Se=e=>({read:t=>fe(e,t)});export{E as AUTH_AUDIT_TABLE,ue as appendAuthAuditEntry,Se as createAuthAuditReader,L as ensureAuthAuditTable,fe as readAuthAuditLog};
12
+ )`,[]);try{await e.run(`ALTER TABLE "${A}" ADD COLUMN target_email TEXT`,[])}catch(t){if(!(t instanceof Error?t.message.toLowerCase():String(t).toLowerCase()).includes("duplicate column"))throw t}},_=new WeakMap,D=e=>{const t=_.get(e);if(t)return t;const n=Oe(e);return _.set(e,n),n.catch(()=>_.delete(e)),n},Le=async(e,t,n={})=>{await D(e);let s;if(t.detail!==void 0){const r=t.outcome==="failure"?await ye(t.detail,n.hashKey):t.detail;s=n.redactDetail===!1?r:we(r)}return await e.run(`INSERT INTO "${A}" (ts, event, outcome, actor_id, actor_email, target_email, ip, user_agent, detail) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[t.ts,t.event,t.outcome,t.actorId??p,t.actorEmail??p,t.targetEmail??p,t.ip??p,t.userAgent??p,s===void 0?p:JSON.stringify(s)]),typeof n.retention=="number"&&n.retention>0&&await e.run(`DELETE FROM "${A}" WHERE seq <= (SELECT MAX(seq) - ? FROM "${A}")`,[n.retention]),{...t,detail:s}},Re=async(e,t={})=>{await D(e);const n=Number.isFinite(t.limit)?Math.max(1,Math.min(t.limit,be)):Ie,s=["seq > ?"],r=[t.sinceSeq??0],i=t.sinceSeq===void 0?"DESC":"ASC";return t.actorId!==void 0&&(s.push("actor_id = ?"),r.push(t.actorId)),t.event!==void 0&&(s.push("event = ?"),r.push(t.event)),r.push(n),(await e.all(`SELECT seq, ts, event, outcome, actor_id, actor_email, target_email, ip, user_agent, detail FROM "${A}" WHERE ${s.join(" AND ")} ORDER BY seq ${i} LIMIT ?`,r)).map(a=>{const c={event:S(a.event)??"",outcome:a.outcome==="failure"?"failure":"success",seq:Number(a.seq),ts:Number(a.ts)},d=[["actorId","actor_id"],["actorEmail","actor_email"],["targetEmail","target_email"],["ip","ip"],["userAgent","user_agent"]];for(const[E,C]of d){const T=S(a[C]);T!==void 0&&(c[E]=T)}const h=S(a.detail);if(h!==void 0)try{const E=JSON.parse(h);typeof E=="object"&&E!==null&&!Array.isArray(E)&&(c.detail=E)}catch{}return c})},Ne=e=>({read:t=>Re(e,t)});export{A as AUTH_AUDIT_TABLE,Le as appendAuthAuditEntry,Ne as createAuthAuditReader,D as ensureAuthAuditTable,Re as readAuthAuditLog};
package/dist/index.d.mts CHANGED
@@ -56,6 +56,7 @@ interface AuditHookContext {
56
56
  context?: {
57
57
  newSession?: {
58
58
  session?: {
59
+ impersonatedBy?: string;
59
60
  userId?: string;
60
61
  };
61
62
  user?: {
@@ -64,8 +65,10 @@ interface AuditHookContext {
64
65
  };
65
66
  } | null;
66
67
  returned?: unknown;
68
+ secret?: string;
67
69
  session?: {
68
70
  session?: {
71
+ impersonatedBy?: string;
69
72
  userId?: string;
70
73
  };
71
74
  user?: {
@@ -139,6 +142,12 @@ interface AuditHookContext {
139
142
  * `/oauth2/callback/` is inside `better-auth/plugins/oauth-popup`, which
140
143
  * `plugins.ts` does not re-export — so today the branch fires for the core
141
144
  * callback, and stays correct if the other becomes reachable.
145
+ *
146
+ * The plugin endpoints in {@link SUFFIX_EVENTS} are pinned against the installed
147
+ * better-auth by `__tests__/audit-endpoint-coverage.test.ts`, which fails on any
148
+ * endpoint it does not classify, so an upgrade cannot add one silently.
149
+ *
150
+ * The exact table {@link SUFFIX_EVENTS} is consulted first, then the substring branches.
142
151
  */
143
152
  declare const eventForPath: (path: string) => AuthAuditEvent | undefined;
144
153
  /**
@@ -184,6 +193,9 @@ declare const buildAuditEntry: (context: AuditHookContext, { now, trustProxyHead
184
193
  * | `/callback/:id` (social + generic-oauth) | _(not recorded)_ | `sign-in` |
185
194
  * | `/magic-link/verify` | _(not recorded)_ | `sign-in` |
186
195
  * | `/two-factor/verify-totp` / `-otp` / `-backup-code`| _(not recorded)_ | `sign-in` |
196
+ * | `/device/token` | `token-refresh` | `sign-in` |
197
+ * | `/request-password-reset`, `/forget-password`, `…/forget-password/email-otp`, `…/request-password-reset` | `password-reset` | `password-reset-request` |
198
+ * | Any event in a session that is impersonating another user | actor is the impersonated user, with `actorEmail` | actor is the administrator (`impersonatedBy`), with no `actorEmail`; the impersonated user is `detail.targetUserId` |
187
199
  *
188
200
  * A caller matching on `event === "sign-in"` now sees FEWER events for
189
201
  * `/sign-in/social` and `/sign-in/magic-link` (they never actually authenticated
package/dist/index.d.ts CHANGED
@@ -56,6 +56,7 @@ interface AuditHookContext {
56
56
  context?: {
57
57
  newSession?: {
58
58
  session?: {
59
+ impersonatedBy?: string;
59
60
  userId?: string;
60
61
  };
61
62
  user?: {
@@ -64,8 +65,10 @@ interface AuditHookContext {
64
65
  };
65
66
  } | null;
66
67
  returned?: unknown;
68
+ secret?: string;
67
69
  session?: {
68
70
  session?: {
71
+ impersonatedBy?: string;
69
72
  userId?: string;
70
73
  };
71
74
  user?: {
@@ -139,6 +142,12 @@ interface AuditHookContext {
139
142
  * `/oauth2/callback/` is inside `better-auth/plugins/oauth-popup`, which
140
143
  * `plugins.ts` does not re-export — so today the branch fires for the core
141
144
  * callback, and stays correct if the other becomes reachable.
145
+ *
146
+ * The plugin endpoints in {@link SUFFIX_EVENTS} are pinned against the installed
147
+ * better-auth by `__tests__/audit-endpoint-coverage.test.ts`, which fails on any
148
+ * endpoint it does not classify, so an upgrade cannot add one silently.
149
+ *
150
+ * The exact table {@link SUFFIX_EVENTS} is consulted first, then the substring branches.
142
151
  */
143
152
  declare const eventForPath: (path: string) => AuthAuditEvent | undefined;
144
153
  /**
@@ -184,6 +193,9 @@ declare const buildAuditEntry: (context: AuditHookContext, { now, trustProxyHead
184
193
  * | `/callback/:id` (social + generic-oauth) | _(not recorded)_ | `sign-in` |
185
194
  * | `/magic-link/verify` | _(not recorded)_ | `sign-in` |
186
195
  * | `/two-factor/verify-totp` / `-otp` / `-backup-code`| _(not recorded)_ | `sign-in` |
196
+ * | `/device/token` | `token-refresh` | `sign-in` |
197
+ * | `/request-password-reset`, `/forget-password`, `…/forget-password/email-otp`, `…/request-password-reset` | `password-reset` | `password-reset-request` |
198
+ * | Any event in a session that is impersonating another user | actor is the impersonated user, with `actorEmail` | actor is the administrator (`impersonatedBy`), with no `actorEmail`; the impersonated user is `detail.targetUserId` |
187
199
  *
188
200
  * A caller matching on `event === "sign-in"` now sees FEWER events for
189
201
  * `/sign-in/social` and `/sign-in/magic-link` (they never actually authenticated
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{l as r,a as o,b as a}from"./packem_shared/adapter-CBZ17jKi.mjs";import{LunoraAuthAdminError as s,createAuthAdmin as u}from"./packem_shared/LunoraAuthAdminError-CxXGd3ni.mjs";import{AUTH_AUDIT_TABLE as A,appendAuthAuditEntry as m,createAuthAuditReader as p,ensureAuthAuditTable as h,readAuthAuditLog as l}from"./audit.mjs";import{authAuditHook as f,buildAuditEntry as x,eventForPath as E,withAuthAudit as D}from"./packem_shared/authAuditHook-DPTKdjBe.mjs";import{R as S,I as c,a as v,L as _}from"./packem_shared/auth-do-DHxBZtyS.mjs";import{createAuth as U,resolveAuthOptions as y}from"./packem_shared/createAuth-Dioo_-mD.mjs";import{authDiscoveryPaths as P,authDiscoveryPathsFor as L,handleAuthDiscoveryRequest as g}from"./packem_shared/authDiscoveryPaths-BtKCs_3V.mjs";import{authDoColumnAdditions as O,authDoSchemaStatements as w}from"./packem_shared/authDoColumnAdditions-UwF3Rl41.mjs";import{createDoAuthWiring as F}from"./packem_shared/createDoAuthWiring-BXyBVIda.mjs";import{emailGateDatabaseHooks as k,withEmailGate as q}from"./packem_shared/emailGateDatabaseHooks-Dvyliwxx.mjs";import{assertEmailAllowed as G,classifyEmail as M,emailGateMiddleware as B,loadEmailDomainLists as W}from"./email-guard.mjs";import{default as Y}from"./packem_shared/isDevEnvironment-yLbPngwn.mjs";import{handleAuthRequest as z}from"./packem_shared/handleAuthRequest-Id9Vv_Tk.mjs";import{createSignUpInvitation as K,listSignUpInvitations as Q,pruneSignUpInvitations as X,revokeSignUpInvitation as Z}from"./packem_shared/createSignUpInvitation-CwrPh0XH.mjs";import{legacyIssuerCleanupStatements as tt}from"./packem_shared/legacyIssuerCleanupStatements-D9Kf8OD1.mjs";import{LunoraAuthHeadersError as rt,withAuthPlugins as ot}from"./middleware.mjs";import{default as it}from"./schema.mjs";import{sessionPresets as ut,validateSessionPolicy as nt}from"./packem_shared/sessionPresets-C867Mlo4.mjs";import{resolveSessionIdentity as mt}from"./packem_shared/resolveSessionIdentity-CNjGy6Pb.mjs";import{c as ht,d as lt}from"./packem_shared/sql-store-uMubPYI9.mjs";import{createMemoryAuthStore as ft,matchesWhere as xt}from"./store.mjs";import{TURNSTILE_VERIFY_ENDPOINT as Dt,verifyTurnstile as Tt}from"./turnstile.mjs";import{verifyTurnstileMiddleware as ct}from"./turnstile-middleware.mjs";import{DEFAULT_AUTH_BASE_PATH as _t}from"./packem_shared/DEFAULT_AUTH_BASE_PATH-C3SqYG3N.mjs";export{A as AUTH_AUDIT_TABLE,S as AUTH_DO_AUDIT_PATH,c as AUTH_DO_SECRET_HEADER,v as AUTH_DO_SESSION_PATH,_t as DEFAULT_AUTH_BASE_PATH,s as LunoraAuthAdminError,_ as LunoraAuthDO,rt as LunoraAuthHeadersError,Dt as TURNSTILE_VERIFY_ENDPOINT,m as appendAuthAuditEntry,G as assertEmailAllowed,f as authAuditHook,P as authDiscoveryPaths,L as authDiscoveryPathsFor,O as authDoColumnAdditions,w as authDoSchemaStatements,it as authTables,x as buildAuditEntry,M as classifyEmail,U as createAuth,u as createAuthAdmin,p as createAuthAuditReader,F as createDoAuthWiring,ft as createMemoryAuthStore,K as createSignUpInvitation,ht as createSqlAuthStore,lt as d1Executor,k as emailGateDatabaseHooks,B as emailGateMiddleware,h as ensureAuthAuditTable,E as eventForPath,g as handleAuthDiscoveryRequest,z as handleAuthRequest,Y as isDevEnvironment,tt as legacyIssuerCleanupStatements,Q as listSignUpInvitations,W as loadEmailDomainLists,r as lunoraAuthAdapter,o as lunoraD1Adapter,a as lunoraDoAdapter,xt as matchesWhere,X as pruneSignUpInvitations,l as readAuthAuditLog,y as resolveAuthOptions,mt as resolveSessionIdentity,Z as revokeSignUpInvitation,ut as sessionPresets,nt as validateSessionPolicy,Tt as verifyTurnstile,ct as verifyTurnstileMiddleware,D as withAuthAudit,ot as withAuthPlugins,q as withEmailGate};
1
+ import{l as r,a as o,b as a}from"./packem_shared/adapter-CBZ17jKi.mjs";import{LunoraAuthAdminError as s,createAuthAdmin as u}from"./packem_shared/LunoraAuthAdminError-CxXGd3ni.mjs";import{AUTH_AUDIT_TABLE as A,appendAuthAuditEntry as m,createAuthAuditReader as p,ensureAuthAuditTable as h,readAuthAuditLog as l}from"./audit.mjs";import{authAuditHook as f,buildAuditEntry as x,eventForPath as E,withAuthAudit as D}from"./packem_shared/authAuditHook-IhGVx_fz.mjs";import{R as S,I as c,a as v,L as _}from"./packem_shared/auth-do-vDGawDob.mjs";import{createAuth as U,resolveAuthOptions as y}from"./packem_shared/createAuth-Dioo_-mD.mjs";import{authDiscoveryPaths as P,authDiscoveryPathsFor as L,handleAuthDiscoveryRequest as g}from"./packem_shared/authDiscoveryPaths-BtKCs_3V.mjs";import{authDoColumnAdditions as O,authDoSchemaStatements as w}from"./packem_shared/authDoColumnAdditions-UwF3Rl41.mjs";import{createDoAuthWiring as F}from"./packem_shared/createDoAuthWiring-Te19LXi-.mjs";import{emailGateDatabaseHooks as k,withEmailGate as q}from"./packem_shared/emailGateDatabaseHooks-Dvyliwxx.mjs";import{assertEmailAllowed as G,classifyEmail as M,emailGateMiddleware as B,loadEmailDomainLists as W}from"./email-guard.mjs";import{default as Y}from"./packem_shared/isDevEnvironment-yLbPngwn.mjs";import{handleAuthRequest as z}from"./packem_shared/handleAuthRequest-Id9Vv_Tk.mjs";import{createSignUpInvitation as K,listSignUpInvitations as Q,pruneSignUpInvitations as X,revokeSignUpInvitation as Z}from"./packem_shared/createSignUpInvitation-CwrPh0XH.mjs";import{legacyIssuerCleanupStatements as tt}from"./packem_shared/legacyIssuerCleanupStatements-D9Kf8OD1.mjs";import{LunoraAuthHeadersError as rt,withAuthPlugins as ot}from"./middleware.mjs";import{default as it}from"./schema.mjs";import{sessionPresets as ut,validateSessionPolicy as nt}from"./packem_shared/sessionPresets-C867Mlo4.mjs";import{resolveSessionIdentity as mt}from"./packem_shared/resolveSessionIdentity-CNjGy6Pb.mjs";import{c as ht,d as lt}from"./packem_shared/sql-store-uMubPYI9.mjs";import{createMemoryAuthStore as ft,matchesWhere as xt}from"./store.mjs";import{TURNSTILE_VERIFY_ENDPOINT as Dt,verifyTurnstile as Tt}from"./turnstile.mjs";import{verifyTurnstileMiddleware as ct}from"./turnstile-middleware.mjs";import{DEFAULT_AUTH_BASE_PATH as _t}from"./packem_shared/DEFAULT_AUTH_BASE_PATH-C3SqYG3N.mjs";export{A as AUTH_AUDIT_TABLE,S as AUTH_DO_AUDIT_PATH,c as AUTH_DO_SECRET_HEADER,v as AUTH_DO_SESSION_PATH,_t as DEFAULT_AUTH_BASE_PATH,s as LunoraAuthAdminError,_ as LunoraAuthDO,rt as LunoraAuthHeadersError,Dt as TURNSTILE_VERIFY_ENDPOINT,m as appendAuthAuditEntry,G as assertEmailAllowed,f as authAuditHook,P as authDiscoveryPaths,L as authDiscoveryPathsFor,O as authDoColumnAdditions,w as authDoSchemaStatements,it as authTables,x as buildAuditEntry,M as classifyEmail,U as createAuth,u as createAuthAdmin,p as createAuthAuditReader,F as createDoAuthWiring,ft as createMemoryAuthStore,K as createSignUpInvitation,ht as createSqlAuthStore,lt as d1Executor,k as emailGateDatabaseHooks,B as emailGateMiddleware,h as ensureAuthAuditTable,E as eventForPath,g as handleAuthDiscoveryRequest,z as handleAuthRequest,Y as isDevEnvironment,tt as legacyIssuerCleanupStatements,Q as listSignUpInvitations,W as loadEmailDomainLists,r as lunoraAuthAdapter,o as lunoraD1Adapter,a as lunoraDoAdapter,xt as matchesWhere,X as pruneSignUpInvitations,l as readAuthAuditLog,y as resolveAuthOptions,mt as resolveSessionIdentity,Z as revokeSignUpInvitation,ut as sessionPresets,nt as validateSessionPolicy,Tt as verifyTurnstile,ct as verifyTurnstileMiddleware,D as withAuthAudit,ot as withAuthPlugins,q as withEmailGate};
@@ -1 +1 @@
1
- import{I as _,L as S,R as T,a as s}from"./auth-do-DHxBZtyS.mjs";import"./adapter-CBZ17jKi.mjs";import"../audit.mjs";import"./createAuth-Dioo_-mD.mjs";import"./authDiscoveryPaths-BtKCs_3V.mjs";import"./authDoColumnAdditions-UwF3Rl41.mjs";import"./handleAuthRequest-Id9Vv_Tk.mjs";import"./legacyIssuerCleanupStatements-D9Kf8OD1.mjs";import"./resolveSessionIdentity-CNjGy6Pb.mjs";export{_ as INTERNAL_SECRET_HEADER,S as LunoraAuthDO,T as READ_AUDIT_PATH,s as RESOLVE_SESSION_PATH};
1
+ import{I as _,L as S,R as T,a as s}from"./auth-do-vDGawDob.mjs";import"./adapter-CBZ17jKi.mjs";import"../audit.mjs";import"./createAuth-Dioo_-mD.mjs";import"./authDiscoveryPaths-BtKCs_3V.mjs";import"./authDoColumnAdditions-UwF3Rl41.mjs";import"./handleAuthRequest-Id9Vv_Tk.mjs";import"./legacyIssuerCleanupStatements-D9Kf8OD1.mjs";import"./resolveSessionIdentity-CNjGy6Pb.mjs";export{_ as INTERNAL_SECRET_HEADER,S as LunoraAuthDO,T as READ_AUDIT_PATH,s as RESOLVE_SESSION_PATH};
@@ -0,0 +1 @@
1
+ import{getAuthTablesWithResolvedIndexes as C}from"@better-auth/core/db/internal";import{LunoraError as N,toErrorBody as J}from"@lunora/errors";import{d as U,b as Y}from"./adapter-CBZ17jKi.mjs";import{AUTH_AUDIT_TABLE as K,ensureAuthAuditTable as Q,createAuthAuditReader as z}from"../audit.mjs";import{resolveAuthOptions as Z,createAuth as ee}from"./createAuth-Dioo_-mD.mjs";import{handleAuthDiscoveryRequest as te}from"./authDiscoveryPaths-BtKCs_3V.mjs";import{authDoSchemaStatements as ne,authDoColumnAdditions as se}from"./authDoColumnAdditions-UwF3Rl41.mjs";import{handleAuthRequest as re}from"./handleAuthRequest-Id9Vv_Tk.mjs";import{decodeWire as D,encodeWire as k}from"@lunora/wire";import{q as c}from"./quote-identifier-CGiYFBvY.mjs";import{schemaDeclaresIssuer as oe,legacyIssuerCleanupStatements as ae,indexesReferencingIssuer as ie}from"./legacyIssuerCleanupStatements-D9Kf8OD1.mjs";import{parseClaimNames as ce,resolveSessionIdentity as ue}from"./resolveSessionIdentity-CNjGy6Pb.mjs";const le=(t,e)=>{const n=Math.max(t.length,e.length);let s=t.length^e.length;for(let r=0;r<n;r+=1){const o=r<t.length?t.charCodeAt(r):0,a=r<e.length?e.charCodeAt(r):0;s|=o^a}return s===0},j=2166136261,v=16777619,M=(t,e=j)=>{let n=e;for(let s=0;s<t.length;s+=1)n^=t.charCodeAt(s),n=Math.imul(n,v);return(n>>>0).toString(16).padStart(8,"0")},de=t=>`${M(t,j)}${M(t,v)}`,fe="/__lunora/auth/move",w="__lunora_auth_move__",A="__lunora_auth_move_rows__",y="__lunora_auth_purged__",F=100,pe=16,me=100,Ee=2n**64n,H=t=>t.startsWith("sqlite_")||t.startsWith("_cf_")||t===w||t===A||t===y,P=async(t,e)=>t.transaction(async()=>Promise.resolve().then(e)),E=(t,e,...n)=>[...t.sql.exec(e,...n)],f=(t,e,...n)=>{[...t.sql.exec(e,...n)]},O=t=>E(t,"SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").map(e=>String(e.name)).filter(e=>!H(e)),x=(t,e)=>E(t,"SELECT name, pk FROM pragma_table_info(?)",e).map(n=>({name:String(n.name),pk:Number(n.pk)})),L=(t,e)=>x(t,e).map(({name:n})=>n),q=(t,e)=>{const n=x(t,e),s=n.filter(({pk:r})=>r>0).toSorted((r,o)=>r.pk-o.pk).map(({name:r})=>r);return s.length>0?s:n.map(({name:r})=>r)},W=(t,e)=>Number(E(t,`SELECT count(*) AS n FROM ${c(e)}`)[0]?.n??0),B=t=>JSON.stringify(k(t)),I=(t,e)=>BigInt(`0x${de(B(e.map(n=>t[n]??null)))}`),V=(t,e)=>{let n=0,s=0n;for(const r of t)n+=1,s=(s+e(r))%Ee;return`${String(n)}:${s.toString(16)}`},G=(t,e)=>{const n=L(t,e).toSorted((s,r)=>s.localeCompare(r));return V(t.sql.exec(`SELECT * FROM ${c(e)}`),s=>I(s,n))},he=t=>O(t).map(e=>{const n=E(t,"SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?",e)[0]?.sql,s=E(t,"SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ? AND sql IS NOT NULL",e).map(r=>({name:String(r.name),sql:String(r.sql)}));return{columns:L(t,e),indexes:s,name:e,rows:W(t,e),sql:typeof n=="string"?n:""}}),b=(t,e)=>{if(typeof e!="string"||!O(t).includes(e))throw new TypeError(`unknown table ${JSON.stringify(e)}`);return e},Te=(t,e,n)=>{const s=E(t,`SELECT rowid AS "__lunora_rowid__", * FROM ${c(e)} WHERE rowid > ? ORDER BY rowid LIMIT ?`,n,F),r=s.at(-1)?.__lunora_rowid__;return{last:typeof r=="number"?r:void 0,rows:s.map(({__lunora_rowid__:o,...a})=>a)}},Se=(t,e)=>Object.entries(e).filter(([n,s])=>{const r=`SELECT EXISTS (SELECT 1 FROM ${c(b(t,n))} WHERE rowid > ?) AS n`;return Number(E(t,r,s)[0]?.n)===1}).map(([n])=>n),we=t=>L(t,w).length>0,_=t=>we(t)?Object.fromEntries(E(t,`SELECT tbl, after, done, pass, cols, watermark FROM ${c(w)}`).map(e=>[String(e.tbl),{after:Number(e.after),columns:JSON.parse(String(e.cols)),done:e.done===1,pass:Number(e.pass),watermark:Number(e.watermark)}])):{},Re=(t,e,n)=>V(t.sql.exec(`SELECT h FROM ${c(A)} WHERE tbl = ? AND pass = ?`,e,n),s=>BigInt(`0x${String(s.h)}`)),Ne=t=>{f(t,`CREATE TABLE IF NOT EXISTS ${c(w)} (tbl TEXT NOT NULL PRIMARY KEY, after INTEGER NOT NULL, done INTEGER NOT NULL, pass INTEGER NOT NULL, cols TEXT NOT NULL, watermark INTEGER NOT NULL DEFAULT 0)`),f(t,`CREATE TABLE IF NOT EXISTS ${c(A)} (tbl TEXT NOT NULL, k TEXT NOT NULL, h TEXT NOT NULL, pass INTEGER NOT NULL, PRIMARY KEY (tbl, k))`)},Ae=(t,e,n)=>{if(!O(t).includes(e))return 0;const s=q(t,e).map(r=>`u.${c(r)}`).join(", ");return Number(E(t,`SELECT count(*) AS n FROM ${c(e)} u WHERE u.rowid > ? AND NOT EXISTS (SELECT 1 FROM ${c(A)} c WHERE c.tbl = ? AND c.k = json_array(${s}))`,n,e)[0]?.n??0)},ge=/^CREATE TABLE /iu,Oe=/^CREATE (?:UNIQUE )?INDEX /iu,_e=(t,e,n)=>{if(H(e.name))throw new TypeError(`refusing reserved table ${JSON.stringify(e.name)}`);if(!ge.test(e.sql)||e.indexes.some(({sql:r})=>!Oe.test(r)))throw new TypeError(`refusing unexpected DDL for ${JSON.stringify(e.name)}`);if(n.has(e.name)){const r=new Set(L(t,e.name));for(const o of e.columns.filter(a=>!r.has(a)))f(t,`ALTER TABLE ${c(e.name)} ADD COLUMN ${c(o)}`)}else f(t,e.sql);const s=new Set(E(t,"SELECT name FROM sqlite_master WHERE type = 'index'").map(r=>String(r.name)));for(const r of e.indexes.filter(({name:o})=>!s.has(o)))f(t,r.sql)},Le=(t,e,n)=>{Ne(t);const s=Ae(t,n.userTable,_(t)[n.userTable]?.watermark??0);if(s>0&&!n.force)throw new N("AUTH_MOVE_TARGET_NOT_EMPTY",`the pinned auth object has ${String(s)} user(s) the copy did not write; copying into it would merge two user bases — pass force to copy anyway`,{data:{users:s}});const r=new Set(O(t)),o=_(t);for(const i of e){_e(t,i,r);const u=o[i.name],l=JSON.stringify(i.columns.toSorted((d,m)=>d.localeCompare(m)));u===void 0?f(t,`INSERT INTO ${c(w)} (tbl, after, done, pass, cols) VALUES (?, 0, 0, 1, ?)`,i.name,l):f(t,`UPDATE ${c(w)} SET cols = ? WHERE tbl = ?`,l,i.name)}f(t,`UPDATE ${c(w)} SET watermark = (SELECT coalesce(max(rowid), 0) FROM ${c(n.userTable)}) WHERE tbl = ?`,n.userTable);const a=_(t);return{cursors:Object.fromEntries(e.map(({name:i})=>[i,a[i]?.after??0])),done:Object.fromEntries(e.map(({name:i})=>[i,a[i]?.done??!1])),targetRows:Object.fromEntries(e.map(({name:i})=>[i,W(t,i)]))}},X=(t,e,n,s,r)=>E(t,`SELECT ${r.map(o=>c(o)).join(", ")} FROM ${c(e)} WHERE ${n.map(o=>`${c(o)} IS ?`).join(" AND ")} LIMIT 1`,...s)[0],$=(t,e)=>{if(!e)throw new N("AUTH_MOVE_CONFLICT",`a row copied into ${t} collides with a row the pinned auth object holds on its own — nothing from this page was written; pass force to keep the pinned object's rows`,{data:{table:t}});return"conflicts"},ye=t=>t instanceof Error&&t.message.includes("UNIQUE constraint failed"),$e=(t,e)=>{if(e.prior!==void 0)return $(e.table,e.force);try{f(t,`INSERT INTO ${c(e.table)} (${e.columns.map(n=>c(n)).join(", ")}) VALUES (${e.columns.map(()=>"?").join(", ")})`,...e.columns.map(n=>e.row[n]))}catch(n){if(!ye(n))throw n;return $(e.table,e.force)}return"copied"},Ie=(t,e,n)=>{const s=I(n,e.columns).toString(16);return s===e.h?"unchanged":e.prior===void 0||s!==e.prior?$(e.table,e.force):(f(t,`UPDATE ${c(e.table)} SET ${e.columns.map(r=>`${c(r)} = ?`).join(", ")} WHERE ${e.keys.map(r=>`${c(r)} IS ?`).join(" AND ")}`,...e.columns.map(r=>e.row[r]),...e.key),"updated")},be=(t,e,n,s)=>{const{force:r,keys:o,pass:a}=s,i=Object.keys(n).toSorted((h,S)=>h.localeCompare(S));if(i.length+o.length>me)throw new TypeError(`${e} has too many columns to copy`);const u=o.map(h=>n[h]??null),l=B(u),d=I(n,i).toString(16),m=E(t,`SELECT h FROM ${c(A)} WHERE tbl = ? AND k = ?`,e,l)[0]?.h,T={columns:i,force:r,h:d,key:u,keys:o,prior:typeof m=="string"?m:void 0,row:n,table:e},g=T.prior===d?void 0:X(t,e,o,u,i);let p="unchanged";return T.prior!==d&&(p=g===void 0?$e(t,T):Ie(t,T,g)),f(t,`INSERT INTO ${c(A)} (tbl, k, h, pass) VALUES (?, ?, ?, ?) ON CONFLICT (tbl, k) DO UPDATE SET h = excluded.h, pass = excluded.pass`,e,l,d,a),p},De=(t,e,n)=>{const{counts:s,force:r,keys:o,marker:a}=n,i=E(t,`SELECT k, h FROM ${c(A)} WHERE tbl = ? AND pass < ?`,e,a.pass);for(const u of i){const l=D(JSON.parse(String(u.k))),d=X(t,e,o,l,a.columns);d!==void 0&&(I(d,a.columns).toString(16)===String(u.h)?(f(t,`DELETE FROM ${c(e)} WHERE ${o.map(m=>`${c(m)} IS ?`).join(" AND ")}`,...l),s.deleted+=1):s[$(e,r)]+=1),f(t,`DELETE FROM ${c(A)} WHERE tbl = ? AND k = ?`,e,String(u.k))}},Ce=async(t,e,n)=>{const s=_(t)[e];if(s===void 0)throw new TypeError(`table ${JSON.stringify(e)} was not part of this move`);return P(t,()=>{const r={conflicts:0,copied:0,deleted:0,unchanged:0,updated:0},o=q(t,e);for(const a of n.rows)r[be(t,e,a,{force:n.force,keys:o,pass:s.pass})]+=1;return n.final&&De(t,e,{counts:r,force:n.force,keys:o,marker:s}),f(t,`UPDATE ${c(w)} SET after = ?, done = ? WHERE tbl = ?`,n.last,n.final?1:0,e),r})},Ue=async(t,e)=>{const n=O(t);return await P(t,()=>{const s=n.filter(o=>e[o]===void 0);if(s.length>0)throw new N("AUTH_MOVE_INCOMPLETE",`refusing to purge the un-pinned auth object: ${s.join(", ")} not fully copied — run the copy to done: true first`,{data:{unfinished:s}});const r=n.filter(o=>G(t,o)!==e[o]);if(r.length>0)throw new N("AUTH_MOVE_SOURCE_CHANGED",`refusing to purge the un-pinned auth object: ${r.join(", ")} changed since it was copied — run the copy again to carry the changes, then purge`,{data:{changed:r}});for(const o of n)f(t,`DROP TABLE ${c(o)}`);f(t,`CREATE TABLE IF NOT EXISTS ${c(y)} (at INTEGER NOT NULL)`),f(t,`INSERT INTO ${c(y)} (at) VALUES (?)`,Date.now())}),{dropped:n}},Me=t=>{if(L(t,y).length>0)throw new N("AUTH_MOVE_SOURCE_PURGED","the un-pinned auth object was purged after its tables were copied; anything in it now is new, and copying it would delete the pinned object's users")},ke=new Set(["fingerprints","manifest","page","pending","purge"]),je=(t,e,n)=>{e.prepare();const s=_(t);return{copied:n?Object.fromEntries(Object.entries(s).map(([r,o])=>[r,Re(t,r,o.pass)])):{},markers:s,order:e.order()}},ve=(t,e)=>{for(const n of e)f(t,`UPDATE ${c(w)} SET after = 0, done = 0, pass = pass + 1 WHERE tbl = ?`,n);return{}},Fe=[/(?:UNIQUE|NOT NULL|CHECK|FOREIGN KEY|PRIMARY KEY) constraint failed/u,/no such (?:table|column)/u,/datatype mismatch/u,/SQLITE_[A-Z_]+/u],He=t=>{const e=t instanceof Error?t.message:String(t);for(const n of Fe){const s=n.exec(e);if(s)return s[0]}return t instanceof Error?t.name:"unknown"},Pe=async(t,e,n)=>{switch(ke.has(String(e.op))&&Me(t),e.op){case"begin":return n.prepare(),Le(t,e.tables,{force:e.force===!0,userTable:n.userTable()});case"fingerprints":return{fingerprints:Object.fromEntries(O(t).map(s=>[s,G(t,s)]))};case"manifest":return{tables:he(t)};case"page":{const s=Te(t,b(t,e.table),Number(e.after??0));return{last:s.last,rows:k(s.rows)}}case"pending":return{pending:Se(t,e.cursors??{})};case"purge":{const s=await Ue(t,e.expected??{});return n.onPurge(),s}case"rescan":return ve(t,e.tables??[]);case"status":return je(t,n,e.fingerprints===!0);case"write":return Ce(t,b(t,e.table),{final:e.final===!0,force:e.force===!0,last:Number(e.last),rows:D(e.rows)});default:throw new TypeError(`unknown move op ${JSON.stringify(e.op)}`)}},xe=async(t,e,n)=>{try{return await Pe(t,e,n)}catch(s){if(s instanceof N)throw s;console.error("@lunora/auth: auth move step failed",s);const r=String(e.op),o=typeof e.table=="string"?e.table:void 0,a=He(s);throw new N("AUTH_MOVE_FAILED",`auth move ${r}${o===void 0?"":` on ${o}`} failed: ${a}`,{data:{cause:a,op:r,...o===void 0?{}:{table:o}}})}},qe=(t,e)=>{const n=s=>{const r=e.first.indexOf(s);if(r!==-1)return r;const o=e.last.indexOf(s);return o===-1?e.first.length:e.first.length+1+o};return t.toSorted((s,r)=>n(s.name)-n(r.name)||s.name.localeCompare(r.name))},We=(t,e)=>({conflicts:0,copied:0,deleted:0,sourceRows:t.rows,table:t.name,targetRows:e,unchanged:0,updated:0}),at=t=>{const e=async(r,o)=>{const a=await t(r,o);if(!a.ok){let i={};try{const u=await a.json();typeof u.error=="object"&&u.error!==null&&(i=u.error)}catch{}throw new N(i.code??"AUTH_MOVE_FAILED",i.message??`auth move ${String(o.op)} on the ${r} object failed (${String(a.status)})`,{data:i.data,status:a.status})}return a.json()},n=async(r,o)=>{const a=new Set,i={};for(const u of o)r.done[u.name]===!0?i[u.name]=r.cursors[u.name]??0:a.add(u.name);if(Object.keys(i).length>0){const{pending:u}=await e("source",{cursors:i,op:"pending"});for(const l of u)a.add(l)}return a},s=async(r,{begun:o,force:a,pagesLeft:i})=>{const u={conflicts:0,copied:0,deleted:0,targetRows:0,unchanged:0,updated:0};let l=o.cursors[r.name]??0,d=0;for(;;){if(d>=i)return{complete:!1,delta:u,pages:d};d+=1;const m=await e("source",{after:l,op:"page",table:r.name}),T=D(m.rows),g=T.length<F;if(T.length===0&&d===1&&o.done[r.name]===!0)return{complete:!0,delta:u,pages:d};const p=await e("target",{final:g,force:a,last:m.last??l,op:"write",rows:m.rows,table:r.name});if(u.conflicts+=p.conflicts,u.copied+=p.copied,u.deleted+=p.deleted,u.unchanged+=p.unchanged,u.updated+=p.updated,u.targetRows+=p.copied-p.deleted,l=m.last??l,g)return{complete:!0,delta:u,pages:d}}};return{copy:async(r={})=>{const o=r.force===!0,a=await e("target",{op:"status"}),{tables:i}=await e("source",{op:"manifest"}),u=await e("target",{force:o,op:"begin",tables:i}),l=[];let d=0;const m=await n(u,i);for(const h of qe(i,a.order)){const S=We(h,u.targetRows[h.name]??0);if(l.push(S),!m.has(h.name))continue;const R=await s(h,{begun:u,force:o,pagesLeft:pe-d});if(d+=R.pages,S.conflicts+=R.delta.conflicts,S.copied+=R.delta.copied,S.deleted+=R.delta.deleted,S.unchanged+=R.delta.unchanged,S.updated+=R.delta.updated,S.targetRows+=R.delta.targetRows,!R.complete)return{done:!1,tables:l}}const{fingerprints:T}=await e("source",{op:"fingerprints"}),g=await e("target",{fingerprints:!0,op:"status"}),p=Object.keys(T).filter(h=>g.copied[h]!==T[h]);return p.length>0&&await e("target",{op:"rescan",tables:p}),{done:p.length===0,tables:l}},purge:async()=>{const{copied:r,markers:o}=await e("target",{fingerprints:!0,op:"status"}),a=Object.fromEntries(Object.entries(o).filter(([,i])=>i.done).map(([i])=>[i,r[i]]));return e("source",{expected:a,op:"purge"})}}},Be="/__lunora/auth/session",Ve="/__lunora/auth/audit",Ge="x-lunora-auth-do-secret",Xe=t=>{if(t===null||typeof t!="object"||Array.isArray(t))return{error:"body must be a JSON object"};const e={};for(const[n,s]of Object.entries(t))if(n==="limit"||n==="sinceSeq"){if(typeof s!="number"||!Number.isFinite(s))return{error:`"${n}" must be a finite number`};e[n]=s}else if(n==="actorId"||n==="event"){if(typeof s!="string")return{error:`"${n}" must be a string`};e[n]=s}else return{error:`unknown audit read option "${n}"`};return{options:e}};class it{#n;#i;#c;#e;#t;#s=!1;#r={first:["user"],last:[]};constructor(e,n,s={}){this.#e=e.storage,this.#n=U(e.storage),this.#c=n,this.#i=s}#o(){if(this.#t!==void 0)return this.#t;const e=this.#c(),n=Z(e),{tables:s}=C(n);if(this.#r={first:[s.user?.modelName??"user",s.account?.modelName??"account",s.session?.modelName??"session"],last:[K,s.rateLimit?.modelName??"rateLimit"]},!this.#s){for(const r of ne(n))[...this.#e.sql.exec(r)];for(const r of se(n,o=>this.#u(o)))[...this.#e.sql.exec(r)];this.#l(n),this.#s=!0}return this.#t=ee({...e,database:Y(this.#e)}),this.#t}#u(e){return[...this.#e.sql.exec("SELECT name FROM pragma_table_info(?)",e)].map(s=>String(s.name))}#l(e){const{tables:n}=C(e),{account:s}=n;if(s===void 0)return;const r=Object.entries(s.fields).map(([o,a])=>a.fieldName??o);if(!(oe(r)||!this.#u(s.modelName).includes("issuer")))try{const o=[...this.#e.sql.exec("SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ?",s.modelName)].map(a=>({name:String(a.name),sql:typeof a.sql=="string"?a.sql:void 0}));for(const a of ae(s.modelName,ie(o)))[...this.#e.sql.exec(a)]}catch(o){console.error("@lunora/auth: could not drop the reverted `account.issuer` column; if it is still present, sign-ups will fail until it is removed.",o)}}async#d(e){if(!this.#a(e))return Response.json({error:"unauthorized"},{status:401});let n;try{n=await e.json()}catch{return Response.json({error:"invalid body"},{status:400})}const s=Xe(n??{});if("error"in s)return Response.json({error:s.error},{status:400});await Q(this.#n);const r=await z(this.#n).read(s.options);return Response.json({entries:r})}async#f(e){if(e.method!=="POST"||!this.#a(e))return Response.json({error:"unauthorized"},{status:401});try{const n=await e.json(),s=await xe(this.#e,n,{onPurge:()=>{this.#s=!1,this.#t=void 0,this.#n=U(this.#e)},order:()=>this.#r,prepare:()=>{this.#o()},userTable:()=>this.#r.first[0]??"user"});return Response.json(s)}catch(n){const{body:s,redacted:r,status:o}=J(n,{encodeData:a=>a,fallbackCode:"AUTH_MOVE_FAILED",redactedMessage:"auth move failed"});return r&&console.error("@lunora/auth: auth move failed",n),Response.json({error:s},{status:o})}}#a(e){const{internalSecret:n}=this.#i;if(n===void 0||n==="")return!1;const s=e.headers.get(Ge);return s!==null&&le(s,n)}async#p(e){if(!this.#a(e))return Response.json({error:"unauthorized"},{status:401});const n=ce(new URL(e.url).searchParams.get("claims"));return Response.json(await ue(this.#o(),e.headers,n)??{})}async fetch(e){const n=new URL(e.url);if(n.pathname===Be)return this.#p(e);if(n.pathname===Ve)return this.#d(e);if(n.pathname===fe)return this.#f(e);const s=this.#o();return await re(s,e)??await te(s,e)??Response.json({error:"not an auth route"},{status:404})}}export{Ge as I,it as L,fe as M,Ve as R,Be as a,at as c};
@@ -0,0 +1 @@
1
+ import{cyrb53 as k}from"@lunora/values";import{createAuthMiddleware as y}from"better-auth/api";import{o as w}from"./on-cloudflare-edge-Dx6gFjBO.mjs";import{appendAuthAuditEntry as b}from"../audit.mjs";const E=[["/admin/impersonate-user","admin-impersonate-start"],["/admin/stop-impersonating","admin-impersonate-stop"],["/admin/set-user-password","admin-password-set"],["/admin/set-role","admin-role-change"],["/admin/revoke-user-session","admin-session-revoke"],["/admin/revoke-user-sessions","admin-session-revoke"],["/admin/ban-user","admin-user-ban"],["/admin/unban-user","admin-user-unban"],["/admin/create-user","admin-user-create"],["/admin/update-user","admin-user-update"],["/admin/remove-user","admin-user-remove"],["/api-key/create","api-key-create"],["/api-key/update","api-key-update"],["/api-key/delete","api-key-delete"],["/device/approve","device-approve"],["/device/deny","device-deny"],["/device/token","sign-in"],["/email-otp/change-email","email-change"],["/email-otp/request-email-change","email-change-request"],["/change-email","email-change-request"],["/delete-user","user-delete"],["/delete-user/callback","user-delete"],["/delete-anonymous-user","user-delete"],["/forget-password/email-otp","password-reset-request"],["/email-otp/send-verification-otp","password-reset-request"],["/two-factor/generate-backup-codes","mfa-backup-codes-regenerate"],["/one-time-token/generate","one-time-token-create"],["/one-time-token/verify","sign-in"],["/one-tap/callback","sign-in"],["/passkey/verify-authentication","sign-in"],["/passkey/verify-registration","passkey-add"],["/passkey/delete-passkey","passkey-remove"],["/passkey/update-passkey","passkey-rename"],["/phone-number/verify","sign-in"],["/siwe/verify","sign-in"],["/sso/callback","sign-in"],["/multi-session/set-active","session-switch"],["/multi-session/revoke","session-revoke"],["/sso/register","sso-provider-register"],["/sso/update-provider","sso-provider-update"],["/sso/delete-provider","sso-provider-delete"]],I=e=>{const s=i=>e===i||e.endsWith(i);if(s("/sign-up/email")||s("/sign-up"))return"sign-up";if(s("/sign-in/social")||s("/sign-in/magic-link")||s("/sign-in/sso"))return"sign-in-initiated";if(e.includes("/sign-in/")||e.includes("/callback/")||e.includes("/saml2/sp/acs/")||s("/magic-link/verify")||e.includes("/two-factor/verify-"))return"sign-in";if(s("/sign-out")||e.includes("/saml2/logout/")||e.includes("/saml2/sp/slo/"))return"sign-out";if(s("/change-password")||s("/set-password"))return"password-change";if(s("/reset-password"))return"password-reset";if(s("/request-password-reset")||s("/forget-password"))return"password-reset-request";if(s("/verify-email"))return"email-verification";if(e.includes("/two-factor/enable")||e.includes("/totp/enable"))return"mfa-enable";if(e.includes("/two-factor/disable")||e.includes("/totp/disable"))return"mfa-disable";if(s("/refresh-token")||s("/token"))return"token-refresh";if(s("/revoke-session")||s("/revoke-sessions")||s("/revoke-other-sessions"))return"session-revoke";if(s("/link-social"))return"account-link";if(s("/unlink-account"))return"account-unlink"},A=e=>{const s=e.toLowerCase(),i=s.includes("/callback/")||s.includes("/saml2/sp/acs/"),r=i?void 0:E.find(([n])=>s===n||s.endsWith(n))?.[1];return i?"sign-in":r??I(s)},l=(e,s)=>e.headers?.get(s)??e.request?.headers.get(s)??void 0,q=(e,s)=>{if(w()){const i=l(e,"cf-connecting-ip");if(i!==void 0)return i}if(s===!0)return l(e,"x-forwarded-for")?.split(",")[0]?.trim()},a=e=>typeof e=="string"&&e.length>0?e:void 0,f=256,u=e=>{const s=a(e);if(!(s===void 0||s.includes("@")))return s.length<=f?s:`${s.slice(0,f-15)}~${k(s).toString(16).padStart(14,"0")}`},o=(e,s)=>typeof e=="object"&&e!==null&&s in e?e[s]:void 0,g=(e,s)=>{const i=e.context?.session,r=e.context?.newSession;return s==="session-revoke"||s==="session-switch"||s==="email-change"?i??r:r??i},_=(e,s)=>{const i=g(e,s),r=a(i?.session?.impersonatedBy);if(r!==void 0)return{actorId:r};const t=i?.user?.id??i?.session?.userId,n=i?.user?.email;return{...t===void 0?{}:{actorId:t},...n===void 0?{}:{actorEmail:n}}},h=e=>{const s=e.context?.returned;if(s instanceof Error)return"failure";if(typeof s=="object"&&s!==null&&"status"in s){const i=Number(s.status);if(Number.isFinite(i)&&i>=400)return"failure"}return"success"},v=320,S=(e,s)=>{if(s!=="sign-in"&&s!=="sign-in-initiated")return;const i=e.body?.email??e.body?.username;if(!(typeof i!="string"||i.length===0))return i.length>v?i.slice(0,v):i},L=(e,s)=>{const i=g(e,s);if(a(i?.session?.impersonatedBy)!==void 0)return a(i?.user?.id)},T=(e,s)=>{if(!s.startsWith("admin-"))return L(e,s);const i=u(e.body?.userId);if(i!==void 0)return i;if(s==="admin-user-create")return u(o(o(e.context?.returned,"user"),"id"));if(s==="admin-impersonate-stop")return u(o(o(e.context?.session,"user"),"id"))??u(o(o(e.context?.session,"session"),"userId"))},C=e=>{const s=a(e.body?.newEmail)?.toLowerCase();return s!==void 0&&e.context?.newSession?.user?.email===s},D=new Set(["authorization_pending","slow_down"]),N=(e,s)=>{const i=e.path?.toLowerCase()??"",r=e.context?.returned,t=D.has(a(o(o(r,"body"),"error"))??"");let n=s;if(s==="sign-in"&&i.endsWith("/phone-number/verify")){const d=a(o(r,"token"))!==void 0;n=e.body?.updatePhoneNumber!==!0&&(d||h(e)==="failure")?"sign-in":"phone-verification"}else s==="user-delete"&&i.endsWith("/delete-user")&&a(o(r,"message"))==="Verification email sent"?n="user-delete-request":s==="sign-in"&&i.endsWith("/device/token")&&t?n=void 0:s==="email-change-request"&&i.endsWith("/change-email")&&C(e)?n="email-change":s==="password-reset-request"&&i.endsWith("/email-otp/send-verification-otp")&&(n=e.body?.type==="forget-password"?s:void 0);return n},P=(e,s)=>{if(s==="api-key-create")return u(o(e.context?.returned,"id"));if(s==="api-key-update"||s==="api-key-delete")return u(e.body?.keyId)},W=(e,{now:s=Date.now(),trustProxyHeaders:i}={})=>{const r=e.path===void 0?void 0:A(e.path),t=r===void 0?void 0:N(e,r);if(t===void 0)return;const n=q(e,i),d=l(e,"user-agent"),c=S(e,t),p=T(e,t),m=P(e,t);return{..._(e,t),event:t,outcome:h(e),ts:s,...n===void 0?{}:{ip:n},...c===void 0?{}:{targetEmail:c},...d===void 0?{}:{userAgent:d},detail:{path:e.path,...p===void 0?{}:{targetUserId:p},...m===void 0?{}:{keyId:m}}}},F=e=>y(async s=>{try{const i=W(s,{trustProxyHeaders:e.trustProxyHeaders});if(i!==void 0){const r=await b(e.executor,i,{hashKey:s.context.secret,redactDetail:e.redactDetail,retention:e.retention});e.onRecord!==void 0&&await e.onRecord(r)}}catch(i){console.error("@lunora/auth: audit hook failed to record event",i)}}),U=(e,s)=>{const i=F(s),r=e.hooks?.after,t=r?async n=>{const d=await r(n);return await i(n),d}:i;return{...e,hooks:{...e.hooks,after:t}}};export{F as authAuditHook,W as buildAuditEntry,A as eventForPath,U as withAuthAudit};
@@ -1 +1 @@
1
- import{LunoraError as g}from"@lunora/errors";import{I as v,a as E,c as N,R as O,M as T}from"./auth-do-DHxBZtyS.mjs";import{isDiscoveryRequest as S,unlessNotFound as _}from"./authDiscoveryPaths-BtKCs_3V.mjs";import{isAuthRoutePath as I}from"./handleAuthRequest-Id9Vv_Tk.mjs";import{validClaimNames as H}from"./resolveSessionIdentity-CNjGy6Pb.mjs";import{DEFAULT_AUTH_BASE_PATH as P}from"./DEFAULT_AUTH_BASE_PATH-C3SqYG3N.mjs";const U=(n,r,u)=>{const d={};for(const s of u){const a=r[s];Object.hasOwn(n,s)||(typeof a=="boolean"||typeof a=="string"||typeof a=="number"&&Number.isFinite(a))&&(d[s]=a)}return Object.assign(n,d)},k=n=>{const{internalSecret:r,jurisdiction:u,objectName:d="auth"}=n,s=H(n.claims),a=new Set(n.discoveryPaths),w=n.namespace;let{namespace:o}=n;if(o&&u!==void 0){if(typeof o.jurisdiction!="function")throw new TypeError(`@lunora/auth: Durable Object namespace does not support jurisdiction("${u}") — update @cloudflare/workers-types or remove the jurisdiction option`);o=o.jurisdiction(u)}const m=()=>{if(o)return o.get(o.idFromName(d))},R=async(e,t,i)=>{if(!r)return;const l=m();if(!l)return;const f=await l.fetch(new Request(new URL(e,t),{body:JSON.stringify(i),headers:{"content-type":"application/json",[v]:r},method:"POST"}));return f.ok?f:void 0},A=o,b=w&&A&&u!==void 0?N(async(e,t)=>{if(!r)throw new g("AUTH_MOVE_NOT_CONFIGURED","copying the auth object needs its internal secret; set the auth object's `internalSecret`");const i=e==="source"?w:A;return i.get(i.idFromName(d)).fetch(new Request(new URL(T,"https://auth-do.invalid"),{body:JSON.stringify(t),headers:{"content-type":"application/json",[v]:r},method:"POST"}))}):void 0;return{...b===void 0?{}:{jurisdictionMove:b},auditReader:{read:async e=>{const t=await R(O,"https://auth-do.invalid",e);return t?(await t.json())?.entries??[]:[]}},authHandler:async e=>{if(I(new URL(e.url).pathname,P))return m()?.fetch(e)},discoveryHandler:async e=>{if(S(e,a))return _(await m()?.fetch(e))},resolveIdentity:async e=>{if(!r)return null;const t=m();if(!t)return null;const i=new Headers(e.headers);i.set(v,r);const l=new URL(E,e.url);s.length>0&&l.searchParams.set("claims",s.join(","));const f=await t.fetch(new Request(l,{headers:i}));if(!f.ok)return null;const c=await f.json(),p=c?.userId;if(!c||typeof p!="string"||p.length===0)return null;const h={userId:p};for(const j of["email","name","orgId","role","teamId"]){const y=c[j];typeof y=="string"&&y.length>0&&(h[j]=y)}return typeof c.expiresAtMs=="number"&&Number.isFinite(c.expiresAtMs)&&(h.expiresAtMs=c.expiresAtMs),U(h,c,s)}}};export{k as createDoAuthWiring};
1
+ import{LunoraError as g}from"@lunora/errors";import{I as v,a as E,c as N,R as O,M as T}from"./auth-do-vDGawDob.mjs";import{isDiscoveryRequest as S,unlessNotFound as _}from"./authDiscoveryPaths-BtKCs_3V.mjs";import{isAuthRoutePath as I}from"./handleAuthRequest-Id9Vv_Tk.mjs";import{validClaimNames as H}from"./resolveSessionIdentity-CNjGy6Pb.mjs";import{DEFAULT_AUTH_BASE_PATH as P}from"./DEFAULT_AUTH_BASE_PATH-C3SqYG3N.mjs";const U=(n,r,u)=>{const d={};for(const s of u){const a=r[s];Object.hasOwn(n,s)||(typeof a=="boolean"||typeof a=="string"||typeof a=="number"&&Number.isFinite(a))&&(d[s]=a)}return Object.assign(n,d)},k=n=>{const{internalSecret:r,jurisdiction:u,objectName:d="auth"}=n,s=H(n.claims),a=new Set(n.discoveryPaths),w=n.namespace;let{namespace:o}=n;if(o&&u!==void 0){if(typeof o.jurisdiction!="function")throw new TypeError(`@lunora/auth: Durable Object namespace does not support jurisdiction("${u}") — update @cloudflare/workers-types or remove the jurisdiction option`);o=o.jurisdiction(u)}const m=()=>{if(o)return o.get(o.idFromName(d))},R=async(e,t,i)=>{if(!r)return;const l=m();if(!l)return;const f=await l.fetch(new Request(new URL(e,t),{body:JSON.stringify(i),headers:{"content-type":"application/json",[v]:r},method:"POST"}));return f.ok?f:void 0},A=o,b=w&&A&&u!==void 0?N(async(e,t)=>{if(!r)throw new g("AUTH_MOVE_NOT_CONFIGURED","copying the auth object needs its internal secret; set the auth object's `internalSecret`");const i=e==="source"?w:A;return i.get(i.idFromName(d)).fetch(new Request(new URL(T,"https://auth-do.invalid"),{body:JSON.stringify(t),headers:{"content-type":"application/json",[v]:r},method:"POST"}))}):void 0;return{...b===void 0?{}:{jurisdictionMove:b},auditReader:{read:async e=>{const t=await R(O,"https://auth-do.invalid",e);return t?(await t.json())?.entries??[]:[]}},authHandler:async e=>{if(I(new URL(e.url).pathname,P))return m()?.fetch(e)},discoveryHandler:async e=>{if(S(e,a))return _(await m()?.fetch(e))},resolveIdentity:async e=>{if(!r)return null;const t=m();if(!t)return null;const i=new Headers(e.headers);i.set(v,r);const l=new URL(E,e.url);s.length>0&&l.searchParams.set("claims",s.join(","));const f=await t.fetch(new Request(l,{headers:i}));if(!f.ok)return null;const c=await f.json(),p=c?.userId;if(!c||typeof p!="string"||p.length===0)return null;const h={userId:p};for(const j of["email","name","orgId","role","teamId"]){const y=c[j];typeof y=="string"&&y.length>0&&(h[j]=y)}return typeof c.expiresAtMs=="number"&&Number.isFinite(c.expiresAtMs)&&(h.expiresAtMs=c.expiresAtMs),U(h,c,s)}}};export{k as createDoAuthWiring};
package/dist/worker.mjs CHANGED
@@ -1 +1 @@
1
- import{a as t}from"./packem_shared/adapter-CBZ17jKi.mjs";import{createAuthAdmin as a}from"./packem_shared/LunoraAuthAdminError-CxXGd3ni.mjs";import{createAuthAuditReader as h}from"./audit.mjs";import{createAuth as p}from"./packem_shared/createAuth-Dioo_-mD.mjs";import{authDiscoveryPathsFor as x,handleAuthDiscoveryRequest as d}from"./packem_shared/authDiscoveryPaths-BtKCs_3V.mjs";import{createDoAuthWiring as A}from"./packem_shared/createDoAuthWiring-BXyBVIda.mjs";import{handleAuthRequest as c}from"./packem_shared/handleAuthRequest-Id9Vv_Tk.mjs";import{resolveSessionIdentity as l}from"./packem_shared/resolveSessionIdentity-CNjGy6Pb.mjs";import{d as v}from"./packem_shared/sql-store-uMubPYI9.mjs";export{x as authDiscoveryPathsFor,p as createAuth,a as createAuthAdmin,h as createAuthAuditReader,A as createDoAuthWiring,v as d1Executor,d as handleAuthDiscoveryRequest,c as handleAuthRequest,t as lunoraD1Adapter,l as resolveSessionIdentity};
1
+ import{a as t}from"./packem_shared/adapter-CBZ17jKi.mjs";import{createAuthAdmin as a}from"./packem_shared/LunoraAuthAdminError-CxXGd3ni.mjs";import{createAuthAuditReader as h}from"./audit.mjs";import{createAuth as p}from"./packem_shared/createAuth-Dioo_-mD.mjs";import{authDiscoveryPathsFor as x,handleAuthDiscoveryRequest as d}from"./packem_shared/authDiscoveryPaths-BtKCs_3V.mjs";import{createDoAuthWiring as A}from"./packem_shared/createDoAuthWiring-Te19LXi-.mjs";import{handleAuthRequest as c}from"./packem_shared/handleAuthRequest-Id9Vv_Tk.mjs";import{resolveSessionIdentity as l}from"./packem_shared/resolveSessionIdentity-CNjGy6Pb.mjs";import{d as v}from"./packem_shared/sql-store-uMubPYI9.mjs";export{x as authDiscoveryPathsFor,p as createAuth,a as createAuthAdmin,h as createAuthAuditReader,A as createDoAuthWiring,v as d1Executor,d as handleAuthDiscoveryRequest,c as handleAuthRequest,t as lunoraD1Adapter,l as resolveSessionIdentity};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/auth",
3
- "version": "1.0.0-alpha.263",
3
+ "version": "1.0.0-alpha.264",
4
4
  "description": "Auth for Lunora — a thin better-auth wrapper: email/password, OAuth, plugins, D1-backed",
5
5
  "keywords": [
6
6
  "auth",
@@ -1 +0,0 @@
1
- import{getAuthTablesWithResolvedIndexes as U}from"@better-auth/core/db/internal";import{LunoraError as w,toErrorBody as Y}from"@lunora/errors";import{d as C,b as K}from"./adapter-CBZ17jKi.mjs";import{AUTH_AUDIT_TABLE as Q,ensureAuthAuditTable as z,createAuthAuditReader as Z}from"../audit.mjs";import{resolveAuthOptions as ee,createAuth as te}from"./createAuth-Dioo_-mD.mjs";import{handleAuthDiscoveryRequest as ne}from"./authDiscoveryPaths-BtKCs_3V.mjs";import{authDoSchemaStatements as re,authDoColumnAdditions as se}from"./authDoColumnAdditions-UwF3Rl41.mjs";import{handleAuthRequest as oe}from"./handleAuthRequest-Id9Vv_Tk.mjs";import{decodeWire as I,encodeWire as v}from"@lunora/wire";import{q as a}from"./quote-identifier-CGiYFBvY.mjs";import{schemaDeclaresIssuer as ie,legacyIssuerCleanupStatements as ae,indexesReferencingIssuer as ce}from"./legacyIssuerCleanupStatements-D9Kf8OD1.mjs";import{parseClaimNames as ue,resolveSessionIdentity as le}from"./resolveSessionIdentity-CNjGy6Pb.mjs";const fe=(t,e)=>{const n=Math.max(t.length,e.length);let r=t.length^e.length;for(let s=0;s<n;s+=1){const o=s<t.length?t.charCodeAt(s):0,i=s<e.length?e.charCodeAt(s):0;r|=o^i}return r===0},j=2166136261,F=16777619,k=(t,e=j)=>{let n=e;for(let r=0;r<t.length;r+=1)n^=t.charCodeAt(r),n=Math.imul(n,F);return(n>>>0).toString(16).padStart(8,"0")},me=t=>`${k(t,j)}${k(t,F)}`,Ee="/__lunora/auth/move",T="__lunora_auth_move__",R="__lunora_auth_move_rows__",y="__lunora_auth_purged__",x=100,de=16,pe=100,he=2n**64n,H=t=>t.startsWith("sqlite_")||t.startsWith("_cf_")||t===T||t===R||t===y,P=async(t,e)=>t.transaction(async()=>Promise.resolve().then(e)),m=(t,e,...n)=>[...t.sql.exec(e,...n)],u=(t,e,...n)=>{[...t.sql.exec(e,...n)]},_=t=>m(t,"SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").map(e=>String(e.name)).filter(e=>!H(e)),q=(t,e)=>m(t,"SELECT name, pk FROM pragma_table_info(?)",e).map(n=>({name:String(n.name),pk:Number(n.pk)})),g=(t,e)=>q(t,e).map(({name:n})=>n),W=(t,e)=>{const n=q(t,e),r=n.filter(({pk:s})=>s>0).toSorted((s,o)=>s.pk-o.pk).map(({name:s})=>s);return r.length>0?r:n.map(({name:s})=>s)},B=(t,e)=>Number(m(t,`SELECT count(*) AS n FROM ${a(e)}`)[0]?.n??0),V=t=>JSON.stringify(v(t)),b=(t,e)=>BigInt(`0x${me(V(e.map(n=>t[n]??null)))}`),G=(t,e)=>{let n=0,r=0n;for(const s of t)n+=1,r=(r+e(s))%he;return`${String(n)}:${r.toString(16)}`},X=(t,e)=>{const n=g(t,e).toSorted((r,s)=>r.localeCompare(s));return G(t.sql.exec(`SELECT * FROM ${a(e)}`),r=>b(r,n))},Te=t=>_(t).map(e=>{const n=m(t,"SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?",e)[0]?.sql,r=m(t,"SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ? AND sql IS NOT NULL",e).map(s=>({name:String(s.name),sql:String(s.sql)}));return{columns:g(t,e),indexes:r,name:e,rows:B(t,e),sql:typeof n=="string"?n:""}}),M=(t,e)=>{if(typeof e!="string"||!_(t).includes(e))throw new TypeError(`unknown table ${JSON.stringify(e)}`);return e},Se=(t,e,n)=>{const r=m(t,`SELECT rowid AS "__lunora_rowid__", * FROM ${a(e)} WHERE rowid > ? ORDER BY rowid LIMIT ?`,n,x),s=r.at(-1)?.__lunora_rowid__;return{last:typeof s=="number"?s:void 0,rows:r.map(({__lunora_rowid__:o,...i})=>i)}},we=t=>g(t,T).length>0,O=t=>we(t)?Object.fromEntries(m(t,`SELECT tbl, after, done, pass, cols, watermark FROM ${a(T)}`).map(e=>[String(e.tbl),{after:Number(e.after),columns:JSON.parse(String(e.cols)),done:e.done===1,pass:Number(e.pass),watermark:Number(e.watermark)}])):{},Re=(t,e,n)=>G(t.sql.exec(`SELECT h FROM ${a(R)} WHERE tbl = ? AND pass = ?`,e,n),r=>BigInt(`0x${String(r.h)}`)),Ne=t=>{u(t,`CREATE TABLE IF NOT EXISTS ${a(T)} (tbl TEXT NOT NULL PRIMARY KEY, after INTEGER NOT NULL, done INTEGER NOT NULL, pass INTEGER NOT NULL, cols TEXT NOT NULL, watermark INTEGER NOT NULL DEFAULT 0)`),u(t,`CREATE TABLE IF NOT EXISTS ${a(R)} (tbl TEXT NOT NULL, k TEXT NOT NULL, h TEXT NOT NULL, pass INTEGER NOT NULL, PRIMARY KEY (tbl, k))`)},Ae=(t,e,n)=>{if(!_(t).includes(e))return 0;const r=W(t,e).map(s=>`u.${a(s)}`).join(", ");return Number(m(t,`SELECT count(*) AS n FROM ${a(e)} u WHERE u.rowid > ? AND NOT EXISTS (SELECT 1 FROM ${a(R)} c WHERE c.tbl = ? AND c.k = json_array(${r}))`,n,e)[0]?.n??0)},_e=/^CREATE TABLE /iu,Oe=/^CREATE (?:UNIQUE )?INDEX /iu,ge=(t,e,n)=>{if(H(e.name))throw new TypeError(`refusing reserved table ${JSON.stringify(e.name)}`);if(!_e.test(e.sql)||e.indexes.some(({sql:s})=>!Oe.test(s)))throw new TypeError(`refusing unexpected DDL for ${JSON.stringify(e.name)}`);if(n.has(e.name)){const s=new Set(g(t,e.name));for(const o of e.columns.filter(i=>!s.has(i)))u(t,`ALTER TABLE ${a(e.name)} ADD COLUMN ${a(o)}`)}else u(t,e.sql);const r=new Set(m(t,"SELECT name FROM sqlite_master WHERE type = 'index'").map(s=>String(s.name)));for(const s of e.indexes.filter(({name:o})=>!r.has(o)))u(t,s.sql)},Le=(t,e,n)=>{Ne(t);const r=Ae(t,n.userTable,O(t)[n.userTable]?.watermark??0);if(r>0&&!n.force)throw new w("AUTH_MOVE_TARGET_NOT_EMPTY",`the pinned auth object has ${String(r)} user(s) the copy did not write; copying into it would merge two user bases — pass force to copy anyway`,{data:{users:r}});const s=new Set(_(t)),o=O(t);for(const c of e){ge(t,c,s);const f=o[c.name],E=JSON.stringify(c.columns.toSorted((d,p)=>d.localeCompare(p)));f===void 0?u(t,`INSERT INTO ${a(T)} (tbl, after, done, pass, cols) VALUES (?, 0, 0, 1, ?)`,c.name,E):u(t,`UPDATE ${a(T)} SET cols = ? WHERE tbl = ?`,E,c.name)}u(t,`UPDATE ${a(T)} SET watermark = (SELECT coalesce(max(rowid), 0) FROM ${a(n.userTable)}) WHERE tbl = ?`,n.userTable);const i=O(t);return{cursors:Object.fromEntries(e.map(({name:c})=>[c,i[c]?.after??0])),done:Object.fromEntries(e.map(({name:c})=>[c,i[c]?.done??!1])),targetRows:Object.fromEntries(e.map(({name:c})=>[c,B(t,c)]))}},J=(t,e,n,r,s)=>m(t,`SELECT ${s.map(o=>a(o)).join(", ")} FROM ${a(e)} WHERE ${n.map(o=>`${a(o)} IS ?`).join(" AND ")} LIMIT 1`,...r)[0],$=(t,e)=>{if(!e)throw new w("AUTH_MOVE_CONFLICT",`a row copied into ${t} collides with a row the pinned auth object holds on its own — nothing from this page was written; pass force to keep the pinned object's rows`,{data:{table:t}});return"conflicts"},ye=t=>t instanceof Error&&t.message.includes("UNIQUE constraint failed"),$e=(t,e)=>{if(e.prior!==void 0)return $(e.table,e.force);try{u(t,`INSERT INTO ${a(e.table)} (${e.columns.map(n=>a(n)).join(", ")}) VALUES (${e.columns.map(()=>"?").join(", ")})`,...e.columns.map(n=>e.row[n]))}catch(n){if(!ye(n))throw n;return $(e.table,e.force)}return"copied"},be=(t,e,n)=>{const r=b(n,e.columns).toString(16);return r===e.h?"unchanged":e.prior===void 0||r!==e.prior?$(e.table,e.force):(u(t,`UPDATE ${a(e.table)} SET ${e.columns.map(s=>`${a(s)} = ?`).join(", ")} WHERE ${e.keys.map(s=>`${a(s)} IS ?`).join(" AND ")}`,...e.columns.map(s=>e.row[s]),...e.key),"updated")},Ie=(t,e,n,r)=>{const{force:s,keys:o,pass:i}=r,c=Object.keys(n).toSorted((S,L)=>S.localeCompare(L));if(c.length+o.length>pe)throw new TypeError(`${e} has too many columns to copy`);const f=o.map(S=>n[S]??null),E=V(f),d=b(n,c).toString(16),p=m(t,`SELECT h FROM ${a(R)} WHERE tbl = ? AND k = ?`,e,E)[0]?.h,l={columns:c,force:s,h:d,key:f,keys:o,prior:typeof p=="string"?p:void 0,row:n,table:e},h=l.prior===d?void 0:J(t,e,o,f,c);let N="unchanged";return l.prior!==d&&(N=h===void 0?$e(t,l):be(t,l,h)),u(t,`INSERT INTO ${a(R)} (tbl, k, h, pass) VALUES (?, ?, ?, ?) ON CONFLICT (tbl, k) DO UPDATE SET h = excluded.h, pass = excluded.pass`,e,E,d,i),N},De=(t,e,n)=>{const{counts:r,force:s,keys:o,marker:i}=n,c=m(t,`SELECT k, h FROM ${a(R)} WHERE tbl = ? AND pass < ?`,e,i.pass);for(const f of c){const E=I(JSON.parse(String(f.k))),d=J(t,e,o,E,i.columns);d!==void 0&&(b(d,i.columns).toString(16)===String(f.h)?(u(t,`DELETE FROM ${a(e)} WHERE ${o.map(p=>`${a(p)} IS ?`).join(" AND ")}`,...E),r.deleted+=1):r[$(e,s)]+=1),u(t,`DELETE FROM ${a(R)} WHERE tbl = ? AND k = ?`,e,String(f.k))}},Ue=async(t,e,n)=>{const r=O(t)[e];if(r===void 0)throw new TypeError(`table ${JSON.stringify(e)} was not part of this move`);return P(t,()=>{const s={conflicts:0,copied:0,deleted:0,unchanged:0,updated:0},o=W(t,e);for(const i of n.rows)s[Ie(t,e,i,{force:n.force,keys:o,pass:r.pass})]+=1;return n.final&&De(t,e,{counts:s,force:n.force,keys:o,marker:r}),u(t,`UPDATE ${a(T)} SET after = ?, done = ? WHERE tbl = ?`,n.last,n.final?1:0,e),s})},Ce=async(t,e)=>{const n=_(t);return await P(t,()=>{const r=n.filter(o=>e[o]===void 0);if(r.length>0)throw new w("AUTH_MOVE_INCOMPLETE",`refusing to purge the un-pinned auth object: ${r.join(", ")} not fully copied — run the copy to done: true first`,{data:{unfinished:r}});const s=n.filter(o=>X(t,o)!==e[o]);if(s.length>0)throw new w("AUTH_MOVE_SOURCE_CHANGED",`refusing to purge the un-pinned auth object: ${s.join(", ")} changed since it was copied — run the copy again to carry the changes, then purge`,{data:{changed:s}});for(const o of n)u(t,`DROP TABLE ${a(o)}`);u(t,`CREATE TABLE IF NOT EXISTS ${a(y)} (at INTEGER NOT NULL)`),u(t,`INSERT INTO ${a(y)} (at) VALUES (?)`,Date.now())}),{dropped:n}},ke=t=>{if(g(t,y).length>0)throw new w("AUTH_MOVE_SOURCE_PURGED","the un-pinned auth object was purged after its tables were copied; anything in it now is new, and copying it would delete the pinned object's users")},Me=new Set(["fingerprints","manifest","page","purge"]),ve=(t,e,n)=>{e.prepare();const r=O(t);return{copied:n?Object.fromEntries(Object.entries(r).map(([s,o])=>[s,Re(t,s,o.pass)])):{},markers:r,order:e.order()}},je=(t,e)=>{for(const n of e)u(t,`UPDATE ${a(T)} SET after = 0, done = 0, pass = pass + 1 WHERE tbl = ?`,n);return{}},Fe=[/(?:UNIQUE|NOT NULL|CHECK|FOREIGN KEY|PRIMARY KEY) constraint failed/u,/no such (?:table|column)/u,/datatype mismatch/u,/SQLITE_[A-Z_]+/u],xe=t=>{const e=t instanceof Error?t.message:String(t);for(const n of Fe){const r=n.exec(e);if(r)return r[0]}return t instanceof Error?t.name:"unknown"},He=async(t,e,n)=>{switch(Me.has(String(e.op))&&ke(t),e.op){case"begin":return n.prepare(),Le(t,e.tables,{force:e.force===!0,userTable:n.userTable()});case"fingerprints":return{fingerprints:Object.fromEntries(_(t).map(r=>[r,X(t,r)]))};case"manifest":return{tables:Te(t)};case"page":{const r=Se(t,M(t,e.table),Number(e.after??0));return{last:r.last,rows:v(r.rows)}}case"purge":{const r=await Ce(t,e.expected??{});return n.onPurge(),r}case"rescan":return je(t,e.tables??[]);case"status":return ve(t,n,e.fingerprints===!0);case"write":return Ue(t,M(t,e.table),{final:e.final===!0,force:e.force===!0,last:Number(e.last),rows:I(e.rows)});default:throw new TypeError(`unknown move op ${JSON.stringify(e.op)}`)}},Pe=async(t,e,n)=>{try{return await He(t,e,n)}catch(r){if(r instanceof w)throw r;console.error("@lunora/auth: auth move step failed",r);const s=String(e.op),o=typeof e.table=="string"?e.table:void 0,i=xe(r);throw new w("AUTH_MOVE_FAILED",`auth move ${s}${o===void 0?"":` on ${o}`} failed: ${i}`,{data:{cause:i,op:s,...o===void 0?{}:{table:o}}})}},qe=(t,e)=>{const n=r=>{const s=e.first.indexOf(r);if(s!==-1)return s;const o=e.last.indexOf(r);return o===-1?e.first.length:e.first.length+1+o};return t.toSorted((r,s)=>n(r.name)-n(s.name)||r.name.localeCompare(s.name))},We=(t,e)=>({conflicts:0,copied:0,deleted:0,sourceRows:t.rows,table:t.name,targetRows:e,unchanged:0,updated:0}),it=t=>{const e=async(n,r)=>{const s=await t(n,r);if(!s.ok){let o={};try{const i=await s.json();typeof i.error=="object"&&i.error!==null&&(o=i.error)}catch{}throw new w(o.code??"AUTH_MOVE_FAILED",o.message??`auth move ${String(r.op)} on the ${n} object failed (${String(s.status)})`,{data:o.data,status:s.status})}return s.json()};return{copy:async(n={})=>{const r=n.force===!0,s=await e("target",{op:"status"}),{tables:o}=await e("source",{op:"manifest"}),i=await e("target",{force:r,op:"begin",tables:o}),c=[];let f=0;for(const l of qe(o,s.order)){const h=We(l,i.targetRows[l.name]??0);let N=i.cursors[l.name]??0;for(c.push(h);;){if(f>=de)return{done:!1,tables:c};f+=1;const S=await e("source",{after:N,op:"page",table:l.name}),L=I(S.rows),D=L.length<x;if(L.length===0&&i.done[l.name]===!0)break;const A=await e("target",{final:D,force:r,last:S.last??N,op:"write",rows:S.rows,table:l.name});if(h.conflicts+=A.conflicts,h.copied+=A.copied,h.deleted+=A.deleted,h.unchanged+=A.unchanged,h.updated+=A.updated,h.targetRows+=A.copied-A.deleted,N=S.last??N,D)break}}const{fingerprints:E}=await e("source",{op:"fingerprints"}),d=await e("target",{fingerprints:!0,op:"status"}),p=Object.keys(E).filter(l=>d.copied[l]!==E[l]);return p.length>0&&await e("target",{op:"rescan",tables:p}),{done:p.length===0,tables:c}},purge:async()=>{const{copied:n,markers:r}=await e("target",{fingerprints:!0,op:"status"}),s=Object.fromEntries(Object.entries(r).filter(([,o])=>o.done).map(([o])=>[o,n[o]]));return e("source",{expected:s,op:"purge"})}}},Be="/__lunora/auth/session",Ve="/__lunora/auth/audit",Ge="x-lunora-auth-do-secret",Xe=t=>{if(t===null||typeof t!="object"||Array.isArray(t))return{error:"body must be a JSON object"};const e={};for(const[n,r]of Object.entries(t))if(n==="limit"||n==="sinceSeq"){if(typeof r!="number"||!Number.isFinite(r))return{error:`"${n}" must be a finite number`};e[n]=r}else if(n==="actorId"||n==="event"){if(typeof r!="string")return{error:`"${n}" must be a string`};e[n]=r}else return{error:`unknown audit read option "${n}"`};return{options:e}};class at{#n;#a;#c;#e;#t;#r=!1;#s={first:["user"],last:[]};constructor(e,n,r={}){this.#e=e.storage,this.#n=C(e.storage),this.#c=n,this.#a=r}#o(){if(this.#t!==void 0)return this.#t;const e=this.#c(),n=ee(e),{tables:r}=U(n);if(this.#s={first:[r.user?.modelName??"user",r.account?.modelName??"account",r.session?.modelName??"session"],last:[Q,r.rateLimit?.modelName??"rateLimit"]},!this.#r){for(const s of re(n))[...this.#e.sql.exec(s)];for(const s of se(n,o=>this.#u(o)))[...this.#e.sql.exec(s)];this.#l(n),this.#r=!0}return this.#t=te({...e,database:K(this.#e)}),this.#t}#u(e){return[...this.#e.sql.exec("SELECT name FROM pragma_table_info(?)",e)].map(r=>String(r.name))}#l(e){const{tables:n}=U(e),{account:r}=n;if(r===void 0)return;const s=Object.entries(r.fields).map(([o,i])=>i.fieldName??o);if(!(ie(s)||!this.#u(r.modelName).includes("issuer")))try{const o=[...this.#e.sql.exec("SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ?",r.modelName)].map(i=>({name:String(i.name),sql:typeof i.sql=="string"?i.sql:void 0}));for(const i of ae(r.modelName,ce(o)))[...this.#e.sql.exec(i)]}catch(o){console.error("@lunora/auth: could not drop the reverted `account.issuer` column; if it is still present, sign-ups will fail until it is removed.",o)}}async#f(e){if(!this.#i(e))return Response.json({error:"unauthorized"},{status:401});let n;try{n=await e.json()}catch{return Response.json({error:"invalid body"},{status:400})}const r=Xe(n??{});if("error"in r)return Response.json({error:r.error},{status:400});await z(this.#n);const s=await Z(this.#n).read(r.options);return Response.json({entries:s})}async#m(e){if(e.method!=="POST"||!this.#i(e))return Response.json({error:"unauthorized"},{status:401});try{const n=await e.json(),r=await Pe(this.#e,n,{onPurge:()=>{this.#r=!1,this.#t=void 0,this.#n=C(this.#e)},order:()=>this.#s,prepare:()=>{this.#o()},userTable:()=>this.#s.first[0]??"user"});return Response.json(r)}catch(n){const{body:r,redacted:s,status:o}=Y(n,{encodeData:i=>i,fallbackCode:"AUTH_MOVE_FAILED",redactedMessage:"auth move failed"});return s&&console.error("@lunora/auth: auth move failed",n),Response.json({error:r},{status:o})}}#i(e){const{internalSecret:n}=this.#a;if(n===void 0||n==="")return!1;const r=e.headers.get(Ge);return r!==null&&fe(r,n)}async#E(e){if(!this.#i(e))return Response.json({error:"unauthorized"},{status:401});const n=ue(new URL(e.url).searchParams.get("claims"));return Response.json(await le(this.#o(),e.headers,n)??{})}async fetch(e){const n=new URL(e.url);if(n.pathname===Be)return this.#E(e);if(n.pathname===Ve)return this.#f(e);if(n.pathname===Ee)return this.#m(e);const r=this.#o();return await oe(r,e)??await ne(r,e)??Response.json({error:"not an auth route"},{status:404})}}export{Ge as I,at as L,Ee as M,Ve as R,Be as a,it as c};
@@ -1 +0,0 @@
1
- import{createAuthMiddleware as d}from"better-auth/api";import{o as c}from"./on-cloudflare-edge-Dx6gFjBO.mjs";import{appendAuthAuditEntry as l}from"../audit.mjs";const f=t=>{const r=t.toLowerCase(),e=s=>r===s||r.endsWith(s);if(e("/sign-up/email")||e("/sign-up"))return"sign-up";if(e("/sign-in/social")||e("/sign-in/magic-link")||e("/sign-in/sso"))return"sign-in-initiated";if(r.includes("/sign-in/")||r.includes("/callback/")||r.includes("/saml2/sp/acs/")||e("/magic-link/verify")||r.includes("/two-factor/verify-"))return"sign-in";if(e("/sign-out")||r.includes("/saml2/logout/")||r.includes("/saml2/sp/slo/"))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(r.includes("/two-factor/enable")||r.includes("/totp/enable"))return"mfa-enable";if(r.includes("/two-factor/disable")||r.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=(t,r)=>t.headers?.get(r)??t.request?.headers.get(r)??void 0,v=(t,r)=>{if(c()){const e=a(t,"cf-connecting-ip");if(e!==void 0)return e}if(r===!0)return a(t,"x-forwarded-for")?.split(",")[0]?.trim()},p=t=>{const r=t.context?.newSession??t.context?.session,e=r?.user?.id??r?.session?.userId,s=r?.user?.email;return{...e===void 0?{}:{actorId:e},...s===void 0?{}:{actorEmail:s}}},g=t=>{const r=t.context?.returned;if(r instanceof Error)return"failure";if(typeof r=="object"&&r!==null&&"status"in r){const e=Number(r.status);if(Number.isFinite(e)&&e>=400)return"failure"}return"success"},u=320,h=(t,r)=>{if(r!=="sign-in"&&r!=="sign-in-initiated")return;const e=t.body?.email??t.body?.username;if(!(typeof e!="string"||e.length===0))return e.length>u?e.slice(0,u):e},m=(t,{now:r=Date.now(),trustProxyHeaders:e}={})=>{const s=t.path===void 0?void 0:f(t.path);if(s===void 0)return;const n=v(t,e),i=a(t,"user-agent"),o=h(t,s);return{...p(t),event:s,outcome:g(t),ts:r,...n===void 0?{}:{ip:n},...o===void 0?{}:{targetEmail:o},...i===void 0?{}:{userAgent:i},detail:{path:t.path}}},w=t=>d(async r=>{try{const e=m(r,{trustProxyHeaders:t.trustProxyHeaders});if(e!==void 0){const s=await l(t.executor,e,{redactDetail:t.redactDetail,retention:t.retention});t.onRecord!==void 0&&await t.onRecord(s)}}catch(e){console.error("@lunora/auth: audit hook failed to record event",e)}}),A=(t,r)=>{const e=w(r),s=t.hooks?.after,n=s?async i=>{const o=await s(i);return await e(i),o}:e;return{...t,hooks:{...t.hooks,after:n}}};export{w as authAuditHook,m as buildAuditEntry,f as eventForPath,A as withAuthAudit};