@stacksjs/auth 0.75.599 → 0.75.602

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.
@@ -1,3 +1,3 @@
1
1
  import{Buffer}from"node:buffer";import{createHmac,randomBytes,timingSafeEqual}from"node:crypto";import{config}from"@stacksjs/config";import{db,enqueueAfterCommit,getDatabaseDialect,mutationCount,parseSqlDateTime,sqlDateTime}from"@stacksjs/database/runtime";import{mail,template}from"@stacksjs/email";import{log}from"@stacksjs/logging";import{normalizeAuthEmail}from"./credential-user";import{greetingName}from"./display-name";import{authLinkBase}from"./link-url";function getVerificationKey(){const appKey=config.app.key;if(typeof appKey!=="string"||appKey.length===0){throw new Error("[auth] config.app.key is not set - email-verification HMAC requires a real APP_KEY. "+"Run `./buddy key:generate` to provision one, or set the APP_KEY env var before booting the app.")}return appKey}function generateVerificationToken(userId,email){const nonce=randomBytes(32).toString("hex");const payload=`${userId}:${normalizeAuthEmail(email)}:${nonce}`;const hash=createHmac("sha256",getVerificationKey()).update(payload).digest("hex");return{token:nonce,hash}}function verifyToken(userId,email,token,storedHash){const payload=`${userId}:${normalizeAuthEmail(email)}:${token}`;const hash=createHmac("sha256",getVerificationKey()).update(payload).digest("hex");const a=Buffer.from(hash);const b=Buffer.from(storedHash);if(a.length!==b.length)return false;return timingSafeEqual(a,b)}function getExpiryMinutes(){const authConfig=config.auth??{};const emailVerification=authConfig.emailVerification;if(emailVerification!=null&&typeof emailVerification==="object"){const ev=emailVerification;if(typeof ev.expire==="number"){return ev.expire}}return 60}function getVerificationUrl(userId,token){const base=authLinkBase();const tpl=config.auth.emailVerification?.url??"/verify-email/{id}/{token}";const filled=tpl.replace("{id}",String(userId)).replace("{token}",token);return/^https?:\/\//.test(filled)?filled:`${base}${filled.startsWith("/")?"":"/"}${filled}`}export function isEmailVerified(user){return user.email_verified_at!=null}export async function sendVerificationEmail(user){await deliverAfterCommit(await prepareVerificationEmail(user))}async function prepareVerificationEmail(user){const expiryMinutes=getExpiryMinutes();const createdAt=new Date;const expiresAt=new Date(createdAt.getTime()+expiryMinutes*60*1000);const prepared=await db.transaction(async()=>{let ownerQuery=db.primary.selectFrom("users").where("id","=",user.id).selectAll();if(getDatabaseDialect()!=="sqlite")ownerQuery=ownerQuery.lockForUpdate();const owner=await ownerQuery.executeTakeFirst();if(!owner||typeof owner.email!=="string"||!owner.email)throw new Error("[auth] Email verification owner no longer exists or has no email.");const{token,hash}=generateVerificationToken(user.id,owner.email);await db.deleteFrom("email_verifications").where("user_id","=",user.id).execute();await db.insertInto("email_verifications").values({user_id:user.id,token:hash,expires_at:sqlDateTime(expiresAt),created_at:sqlDateTime(createdAt)}).executeTakeFirst();const stored=await db.primary.selectFrom("email_verifications").where("user_id","=",user.id).select(["token"]).execute();if(stored.length!==1||stored[0]?.token!==hash)throw new Error("[auth] Email verification could not replace the token.");return{currentUser:{id:Number(owner.id),email:owner.email,name:typeof owner.name==="string"?owner.name:user.name},token}});return()=>deliverVerificationEmail(prepared.currentUser,prepared.token,expiryMinutes)}async function deliverAfterCommit(deliver){if(!enqueueAfterCommit(deliver))await deliver()}async function deliverVerificationEmail(user,token,expiryMinutes){const verificationUrl=getVerificationUrl(user.id,token);const appName=config.app.name||"Stacks";let html;let text;try{const rendered=await template("email-verification",{subject:`Verify Your ${appName} Email Address`,variables:{verificationUrl,expiryMinutes,userName:greetingName(user.name)}});html=rendered.html;text=rendered.text;if(!html&&!text)throw new Error("email-verification template missing or rendered empty")}catch(templateError){const errorMessage=templateError instanceof Error?templateError.message:String(templateError);log.warn(`[email] Email verification template failed, using plain text fallback: ${errorMessage}`);html=undefined;text=`Please verify your email address by visiting: ${verificationUrl}
2
2
 
3
- This link expires in ${expiryMinutes} minutes.`}await mail.sendOrFail({to:user.email,subject:`Verify Your ${appName} Email Address`,text,html})}export async function verifyEmail(userId,token){return db.transaction(async()=>{const record=await db.primary.selectFrom("email_verifications").where("user_id","=",userId).select(["id","token","expires_at"]).executeTakeFirst();if(!record)return{success:false,message:"No verification request found. Please request a new verification email."};const observed=db.deleteFrom("email_verifications").where("user_id","=",userId).where("id","=",record.id).where("token","=",record.token);const claim=record.expires_at==null?observed.whereNull("expires_at"):observed.where("expires_at","=",record.expires_at);const expiresAt=parseSqlDateTime(record.expires_at)??new Date(Number.NaN);if(Number.isNaN(expiresAt.getTime())||Date.now()>=expiresAt.getTime()){await claim.execute();return{success:false,message:"Verification link has expired. Please request a new one."}}let owner=db.primary.selectFrom("users").where("id","=",userId).selectAll();if(getDatabaseDialect()!=="sqlite")owner=owner.lockForUpdate();const user=await owner.executeTakeFirst();if(!user||typeof user.email!=="string"||!user.email)return{success:false,message:"Invalid verification link."};if(!verifyToken(userId,user.email,token,record.token))return{success:false,message:"Invalid verification link."};if(mutationCount(await claim.execute())!==1)return{success:false,message:"Invalid verification link."};if(Date.now()>=expiresAt.getTime())return{success:false,message:"Verification link has expired. Please request a new one."};const updated=await db.updateTable("users").set({email_verified_at:sqlDateTime()}).where("id","=",userId).execute();if(mutationCount(updated)!==1&&user.email_verified_at==null)throw new Error("[auth] Email verification could not update the user.");return{success:true,message:"Email verified successfully."}})}export async function setEmailVerified(userId,verified){await db.updateTable("users").set({email_verified_at:verified?sqlDateTime():null}).where("id","=",userId).execute()}export async function resendVerificationEmail(user){if(isEmailVerified(user)){return{success:false,message:"Email is already verified."}}const outcome=await db.transaction(async()=>{let ownerQuery=db.primary.selectFrom("users").where("id","=",user.id).selectAll();if(getDatabaseDialect()!=="sqlite")ownerQuery=ownerQuery.lockForUpdate();const owner=await ownerQuery.executeTakeFirst();if(!owner)return{result:{success:false,message:"User not found."}};if(isEmailVerified(owner))return{result:{success:false,message:"Email is already verified."}};let existingQuery=db.primary.selectFrom("email_verifications").where("user_id","=",user.id).select(["created_at"]);if(getDatabaseDialect()!=="sqlite")existingQuery=existingQuery.lockForUpdate();const existing=await existingQuery.executeTakeFirst();if(existing){const createdAt=parseSqlDateTime(existing.created_at);const secondsSince=createdAt?(Date.now()-createdAt.getTime())/1000:Number.NaN;if(Number.isNaN(secondsSince)){return{result:{success:false,message:"Please wait a moment before requesting another verification email."}}}if(secondsSince<60){return{result:{success:false,message:`Please wait ${Math.ceil(60-secondsSince)} seconds before requesting another verification email.`}}}}const deliver=await prepareVerificationEmail(user);return{result:{success:true,message:"Verification email sent."},deliver}},getDatabaseDialect()==="sqlite"?{sqliteMode:"immediate",retries:3}:undefined);if(outcome.deliver)await deliverAfterCommit(outcome.deliver);return outcome.result}export const EmailVerification={isVerified:isEmailVerified,send:sendVerificationEmail,verify:verifyEmail,resend:resendVerificationEmail};
3
+ This link expires in ${expiryMinutes} minutes.`}await mail.sendOrFail({tag:"transactional",to:user.email,subject:`Verify Your ${appName} Email Address`,text,html})}export async function verifyEmail(userId,token){return db.transaction(async()=>{const record=await db.primary.selectFrom("email_verifications").where("user_id","=",userId).select(["id","token","expires_at"]).executeTakeFirst();if(!record)return{success:false,message:"No verification request found. Please request a new verification email."};const observed=db.deleteFrom("email_verifications").where("user_id","=",userId).where("id","=",record.id).where("token","=",record.token);const claim=record.expires_at==null?observed.whereNull("expires_at"):observed.where("expires_at","=",record.expires_at);const expiresAt=parseSqlDateTime(record.expires_at)??new Date(Number.NaN);if(Number.isNaN(expiresAt.getTime())||Date.now()>=expiresAt.getTime()){await claim.execute();return{success:false,message:"Verification link has expired. Please request a new one."}}let owner=db.primary.selectFrom("users").where("id","=",userId).selectAll();if(getDatabaseDialect()!=="sqlite")owner=owner.lockForUpdate();const user=await owner.executeTakeFirst();if(!user||typeof user.email!=="string"||!user.email)return{success:false,message:"Invalid verification link."};if(!verifyToken(userId,user.email,token,record.token))return{success:false,message:"Invalid verification link."};if(mutationCount(await claim.execute())!==1)return{success:false,message:"Invalid verification link."};if(Date.now()>=expiresAt.getTime())return{success:false,message:"Verification link has expired. Please request a new one."};const updated=await db.updateTable("users").set({email_verified_at:sqlDateTime()}).where("id","=",userId).execute();if(mutationCount(updated)!==1&&user.email_verified_at==null)throw new Error("[auth] Email verification could not update the user.");return{success:true,message:"Email verified successfully."}})}export async function setEmailVerified(userId,verified){await db.updateTable("users").set({email_verified_at:verified?sqlDateTime():null}).where("id","=",userId).execute()}export async function resendVerificationEmail(user){if(isEmailVerified(user)){return{success:false,message:"Email is already verified."}}const outcome=await db.transaction(async()=>{let ownerQuery=db.primary.selectFrom("users").where("id","=",user.id).selectAll();if(getDatabaseDialect()!=="sqlite")ownerQuery=ownerQuery.lockForUpdate();const owner=await ownerQuery.executeTakeFirst();if(!owner)return{result:{success:false,message:"User not found."}};if(isEmailVerified(owner))return{result:{success:false,message:"Email is already verified."}};let existingQuery=db.primary.selectFrom("email_verifications").where("user_id","=",user.id).select(["created_at"]);if(getDatabaseDialect()!=="sqlite")existingQuery=existingQuery.lockForUpdate();const existing=await existingQuery.executeTakeFirst();if(existing){const createdAt=parseSqlDateTime(existing.created_at);const secondsSince=createdAt?(Date.now()-createdAt.getTime())/1000:Number.NaN;if(Number.isNaN(secondsSince)){return{result:{success:false,message:"Please wait a moment before requesting another verification email."}}}if(secondsSince<60){return{result:{success:false,message:`Please wait ${Math.ceil(60-secondsSince)} seconds before requesting another verification email.`}}}}const deliver=await prepareVerificationEmail(user);return{result:{success:true,message:"Verification email sent."},deliver}},getDatabaseDialect()==="sqlite"?{sqliteMode:"immediate",retries:3}:undefined);if(outcome.deliver)await deliverAfterCommit(outcome.deliver);return outcome.result}export const EmailVerification={isVerified:isEmailVerified,send:sendVerificationEmail,verify:verifyEmail,resend:resendVerificationEmail};
@@ -1,3 +1,3 @@
1
- import{createHash,randomBytes}from"node:crypto";import{config}from"@stacksjs/config";import{db,enqueueAfterCommit,getDatabaseDialect,mutationCount,parseSqlDateTime,sqlDateTime}from"@stacksjs/database/runtime";import{mail,templateByName}from"@stacksjs/email";import{log}from"@stacksjs/logging";import{findAuthUserRowByEmail,normalizeAuthEmail}from"./credential-user";import{authLinkBase}from"./link-url";import{RateLimiter}from"./rate-limiter";function hashToken(raw){return createHash("sha256").update(raw).digest("hex")}function expireMinutes(){return config.auth.magicLink?.expire??15}function safeRedirect(candidate){const fallback=config.auth.magicLink?.redirectDefault??"/";const isLocal=(value)=>{if(typeof value!=="string"||!value.startsWith("/"))return false;try{return new URL(value,"https://stacks.invalid").origin==="https://stacks.invalid"}catch{return false}};return isLocal(candidate)?candidate:isLocal(fallback)?fallback:"/"}async function linkBase(siteId){if(siteId){const primary=await db.selectFrom("site_domains").where("site_id","=",siteId).where("is_primary","=",true).whereNotNull("verified_at").select(["domain"]).executeTakeFirst();if(primary?.domain)return`https://${primary.domain}`;const site=await db.selectFrom("sites").where("id","=",siteId).select(["subdomain"]).executeTakeFirst();const base=config.sites?.baseDomain;if(site?.subdomain&&base)return`https://${site.subdomain}.${base}`}return authLinkBase()}export async function sendMagicLink(email,options={}){const normalized=normalizeAuthEmail(email);const rateKey=`magic:${normalized}`;if(await RateLimiter.isRateLimited(rateKey))return;await RateLimiter.recordFailedAttempt(rateKey);let user=await findAuthUserRowByEmail(normalized);if(!user&&options.createUser){await db.insertInto("users").values({email:normalized,name:normalized.split("@")[0],password:null,created_at:sqlDateTime(new Date),updated_at:sqlDateTime(new Date)}).execute();user=await findAuthUserRowByEmail(normalized)}if(!user)return;const userId=Number(user.id);if(!Number.isSafeInteger(userId)||userId<=0)return;const issued=await db.transaction(async()=>{let ownerQuery=db.primary.selectFrom("users").where("id","=",userId).select(["id","email"]);if(getDatabaseDialect()!=="sqlite")ownerQuery=ownerQuery.lockForUpdate();const owner=await ownerQuery.executeTakeFirst();if(!owner||normalizeAuthEmail(String(owner.email??""))!==normalized)return;const raw=randomBytes(32).toString("base64url");const ttl=options.ttlMinutes??expireMinutes();const token=hashToken(raw);const expiresAt=sqlDateTime(new Date(Date.now()+ttl*60000));await db.deleteFrom("magic_link_tokens").where("email","=",normalized).whereNull("consumed_at").execute();await db.insertInto("magic_link_tokens").values({email:normalized,user_id:userId,token,expires_at:expiresAt,redirect_to:safeRedirect(options.redirectTo),site_id:options.siteId??null,created_at:sqlDateTime(),updated_at:sqlDateTime()}).execute();const stored=await db.primary.selectFrom("magic_link_tokens").where("email","=",normalized).whereNull("consumed_at").select(["token","user_id"]).execute();if(stored.length!==1||stored[0]?.token!==token||String(stored[0]?.user_id)!==String(userId))throw new Error("[auth] Magic-link credential could not be stored.");return{raw,ttl}},getDatabaseDialect()==="sqlite"?{sqliteMode:"immediate",retries:3}:undefined);if(!issued)return;const deliver=()=>deliverMagicLink(normalized,issued.raw,issued.ttl,options.siteId);if(!enqueueAfterCommit(deliver))await deliver()}async function deliverMagicLink(normalized,raw,ttl,siteId){const base=await linkBase(siteId);const tpl=config.auth.magicLink?.url??"/auth/magic/{token}";const filled=tpl.replace("{token}",raw);const linkUrl=/^https?:\/\//.test(filled)?filled:`${base}${filled.startsWith("/")?"":"/"}${filled}`;const appName=config.app.name||"Stacks";let html;let text;try{const rendered=await templateByName("magic-link",{subject:`Sign in to ${appName}`,variables:{linkUrl,expireMinutes:ttl}});if(rendered.html||rendered.text){html=rendered.html;text=rendered.text}}catch{}try{await mail.sendOrFail({to:normalized,subject:`Sign in to ${appName}`,...html?{html}:{},text:text||`Sign in to ${appName}: ${linkUrl}
1
+ import{createHash,randomBytes}from"node:crypto";import{config}from"@stacksjs/config";import{db,enqueueAfterCommit,getDatabaseDialect,mutationCount,parseSqlDateTime,sqlDateTime}from"@stacksjs/database/runtime";import{mail,templateByName}from"@stacksjs/email";import{log}from"@stacksjs/logging";import{findAuthUserRowByEmail,normalizeAuthEmail}from"./credential-user";import{authLinkBase}from"./link-url";import{RateLimiter}from"./rate-limiter";function hashToken(raw){return createHash("sha256").update(raw).digest("hex")}function expireMinutes(){return config.auth.magicLink?.expire??15}function safeRedirect(candidate){const fallback=config.auth.magicLink?.redirectDefault??"/";const isLocal=(value)=>{if(typeof value!=="string"||!value.startsWith("/"))return false;try{return new URL(value,"https://stacks.invalid").origin==="https://stacks.invalid"}catch{return false}};return isLocal(candidate)?candidate:isLocal(fallback)?fallback:"/"}async function linkBase(siteId){if(siteId){const primary=await db.selectFrom("site_domains").where("site_id","=",siteId).where("is_primary","=",true).whereNotNull("verified_at").select(["domain"]).executeTakeFirst();if(primary?.domain)return`https://${primary.domain}`;const site=await db.selectFrom("sites").where("id","=",siteId).select(["subdomain"]).executeTakeFirst();const base=config.sites?.baseDomain;if(site?.subdomain&&base)return`https://${site.subdomain}.${base}`}return authLinkBase()}export async function sendMagicLink(email,options={}){const normalized=normalizeAuthEmail(email);const rateKey=`magic:${normalized}`;if(await RateLimiter.isRateLimited(rateKey))return;await RateLimiter.recordFailedAttempt(rateKey);let user=await findAuthUserRowByEmail(normalized);if(!user&&options.createUser){await db.insertInto("users").values({email:normalized,name:normalized.split("@")[0],password:null,created_at:sqlDateTime(new Date),updated_at:sqlDateTime(new Date)}).execute();user=await findAuthUserRowByEmail(normalized)}if(!user)return;const userId=Number(user.id);if(!Number.isSafeInteger(userId)||userId<=0)return;const issued=await db.transaction(async()=>{let ownerQuery=db.primary.selectFrom("users").where("id","=",userId).select(["id","email"]);if(getDatabaseDialect()!=="sqlite")ownerQuery=ownerQuery.lockForUpdate();const owner=await ownerQuery.executeTakeFirst();if(!owner||normalizeAuthEmail(String(owner.email??""))!==normalized)return;const raw=randomBytes(32).toString("base64url");const ttl=options.ttlMinutes??expireMinutes();const token=hashToken(raw);const expiresAt=sqlDateTime(new Date(Date.now()+ttl*60000));await db.deleteFrom("magic_link_tokens").where("email","=",normalized).whereNull("consumed_at").execute();await db.insertInto("magic_link_tokens").values({email:normalized,user_id:userId,token,expires_at:expiresAt,redirect_to:safeRedirect(options.redirectTo),site_id:options.siteId??null,created_at:sqlDateTime(),updated_at:sqlDateTime()}).execute();const stored=await db.primary.selectFrom("magic_link_tokens").where("email","=",normalized).whereNull("consumed_at").select(["token","user_id"]).execute();if(stored.length!==1||stored[0]?.token!==token||String(stored[0]?.user_id)!==String(userId))throw new Error("[auth] Magic-link credential could not be stored.");return{raw,ttl}},getDatabaseDialect()==="sqlite"?{sqliteMode:"immediate",retries:3}:undefined);if(!issued)return;const deliver=()=>deliverMagicLink(normalized,issued.raw,issued.ttl,options.siteId);if(!enqueueAfterCommit(deliver))await deliver()}async function deliverMagicLink(normalized,raw,ttl,siteId){const base=await linkBase(siteId);const tpl=config.auth.magicLink?.url??"/auth/magic/{token}";const filled=tpl.replace("{token}",raw);const linkUrl=/^https?:\/\//.test(filled)?filled:`${base}${filled.startsWith("/")?"":"/"}${filled}`;const appName=config.app.name||"Stacks";let html;let text;try{const rendered=await templateByName("magic-link",{subject:`Sign in to ${appName}`,variables:{linkUrl,expireMinutes:ttl}});if(rendered.html||rendered.text){html=rendered.html;text=rendered.text}}catch{}try{await mail.sendOrFail({tag:"transactional",to:normalized,subject:`Sign in to ${appName}`,...html?{html}:{},text:text||`Sign in to ${appName}: ${linkUrl}
2
2
 
3
3
  This link works once and expires in ${ttl} minutes. If you didn't request it, ignore this email.`})}catch(error){log.error(`Magic-link email to ${normalized} failed: ${error.message}`)}}export async function consumeMagicLink(raw){const result=await withMagicLink(raw,async(grant)=>grant);return result.ok?result.value:result}export async function withMagicLink(raw,complete){if(!raw||raw.length>255)return{ok:false,reason:"invalid"};const hashed=hashToken(raw);const pending=await db.primary.selectFrom("magic_link_tokens").where("token","=",hashed).select(["user_id","consumed_at","expires_at"]).executeTakeFirst();if(!pending)return{ok:false,reason:"invalid"};if(pending.consumed_at!=null)return{ok:false,reason:"used"};if((parseSqlDateTime(pending.expires_at)?.getTime()??0)<=Date.now())return{ok:false,reason:"expired"};const outcome=await db.transaction(async()=>{let ownerQuery=db.primary.selectFrom("users").where("id","=",pending.user_id).select(["id","email"]);if(getDatabaseDialect()!=="sqlite")ownerQuery=ownerQuery.lockForUpdate();const owner=pending.user_id==null?undefined:await ownerQuery.executeTakeFirst();const grant=await claimMagicLink(hashed);if(!grant.ok)return{result:grant};if(!owner||String(owner.id)!==String(grant.userId)||String(owner.email).trim().toLowerCase()!==grant.email.trim().toLowerCase())return{result:{ok:false,reason:"no-user"}};try{const value=await db.transaction(()=>complete(grant));return{result:{ok:true,value}}}catch(error){return{error}}});if("error"in outcome)throw outcome.error;return outcome.result}async function claimMagicLink(hashed){const now=sqlDateTime(new Date);const claim=await db.updateTable("magic_link_tokens").set({consumed_at:now,updated_at:now}).where("token","=",hashed).whereNull("consumed_at").where("expires_at",">",now).execute();const updated=mutationCount(claim);const row=await db.primary.selectFrom("magic_link_tokens").where("token","=",hashed).select(["user_id","email","expires_at","consumed_at","redirect_to"]).executeTakeFirst();if(!row)return{ok:false,reason:"invalid"};if(updated<1){if(!row.consumed_at&&(parseSqlDateTime(row.expires_at)?.getTime()??0)<=Date.now())return{ok:false,reason:"expired"};return{ok:false,reason:"used"}}if((parseSqlDateTime(row.expires_at)?.getTime()??0)<=Date.now())return{ok:false,reason:"expired"};if(!row.user_id)return{ok:false,reason:"no-user"};return{ok:true,userId:Number(row.user_id),email:row.email,redirectTo:safeRedirect(row.redirect_to)}}export async function pruneMagicLinkTokens(olderThanDays=7){const cutoff=sqlDateTime(new Date(Date.now()-olderThanDays*86400000));await db.deleteFrom("magic_link_tokens").where("expires_at","<",cutoff).execute()}
@@ -5,4 +5,4 @@ import{config}from"@stacksjs/config";import{db,enqueueAfterCommit,getDatabaseDia
5
5
  `).execute();const column=columns[0];if(columns.length!==1||!column||!["datetime","timestamp"].includes(String(column.kind))||!/^[0-6]$/.test(String(column.stamp_precision)))throw new Error("[auth] Cannot verify password_changed_at temporal precision.");const precision=Number(column.stamp_precision);const rows=await db.primary.unsafe(`
6
6
  SELECT (password_changed_at = CAST(? AS DATETIME(${precision}))) AS stamp_matches
7
7
  FROM users WHERE id = ?
8
- `,[stamp,userId]).execute();return rows.length===1&&(rows[0]?.stamp_matches===true||rows[0]?.stamp_matches===1)}async function revokePendingPasswordResets(email){if(typeof email!=="string"||!email)return;try{await db.transaction(async()=>{await deletePasswordResetCredentials(email)})}catch(error){const message=error&&typeof error==="object"&&"message"in error&&typeof error.message==="string"?error.message:String(error);if(/^(?:no such table: (?:main\.)?password_resets|relation "password_resets" does not exist|Table '(?:[^'.]+\.)?password_resets' doesn't exist)$/i.test(message))return;throw error}}export async function revokeAccountCredentials(userId,options={}){if(!Number.isSafeInteger(userId)||userId<=0)throw new TypeError("[auth] revokeAccountCredentials needs a positive integer user id.");if(options.exceptTokenId!==undefined&&(!Number.isSafeInteger(options.exceptTokenId)||options.exceptTokenId<=0))throw new TypeError("[auth] exceptTokenId must be a positive integer.");if(options.tx!==undefined&&!isInTransaction())throw new TypeError("[auth] revokeAccountCredentials was given a tx but is not running inside that transaction.");return db.transaction(async()=>{let ownerQuery=db.primary.selectFrom("users").where("id","=",userId).selectAll();if(getDatabaseDialect()!=="sqlite")ownerQuery=ownerQuery.lockForUpdate();const owner=await ownerQuery.executeTakeFirst();if(!owner)throw new Error("[auth] revokeAccountCredentials: the user does not exist.");let passwordChangedAt=null;const stampValue=sqlDateTime(new Date);if(Object.hasOwn(owner,"password_changed_at")){const stamped=await db.updateTable("users").set({password_changed_at:stampValue}).where("id","=",userId).execute();const changed=mutationCount(stamped);if(changed!==1&&!(changed===0&&getDatabaseDialect()==="mysql"&&await mysqlPasswordStampMatches(userId,stampValue)))throw new Error("[auth] revokeAccountCredentials could not stamp password_changed_at.");passwordChangedAt=parseSqlDateTime(stampValue)}else{log.warn("[auth] password_changed_at column missing - run `buddy migrate`; credentials are revoked without the credential-version stamp")}await revokePendingPasswordResets(owner.email);await revokeTwoFactorChallenges(userId);await revokeMagicLinks(userId);await revokeOAuthSubjectAuthorizationState("users",userId);await revokeTokenPairs(userId,DEFAULT_TOKENABLE_TYPE,options.exceptTokenId);await sessionDestroyAll(userId,options.exceptSessionId!==undefined?{exceptId:options.exceptSessionId}:{});let keptTokenId=null;if(options.exceptTokenId!==undefined&&passwordChangedAt){const rebound=await db.updateTable("oauth_access_tokens").set({created_at:stampValue}).where("id","=",options.exceptTokenId).where("tokenable_id","=",userId).execute();if(mutationCount(rebound)===1){await db.updateTable("oauth_refresh_tokens").set({created_at:stampValue}).where("access_token_id","=",options.exceptTokenId).execute();keptTokenId=options.exceptTokenId}}else if(options.exceptTokenId!==undefined){keptTokenId=options.exceptTokenId}return{passwordChangedAt,keptTokenId}})}export async function changePassword(userId,currentPassword,newPassword,options={}){if(typeof newPassword!=="string"||newPassword.length===0)return{success:false,reason:"invalid-new-password"};const user=await db.primary.selectFrom("users").where("id","=",userId).selectAll().executeTakeFirst();if(!user)return{success:false,reason:"user-not-found"};const storedHash=typeof user.password==="string"?user.password:"";if(typeof currentPassword!=="string"||!storedHash||!await verifyHash(currentPassword,storedHash))return{success:false,reason:"invalid-current-password"};const hashed=await makeHash(newPassword,{algorithm:"bcrypt"});const swept=await withVerifiedPassword(userId,storedHash,async()=>{const updated=await db.updateTable("users").set({password:hashed,...Object.hasOwn(user,"updated_at")?{updated_at:sqlDateTime()}:{}}).where("id","=",userId).execute();if(mutationCount(updated)!==1)throw new Error("[auth] changePassword could not update the password.");return revokeAccountCredentials(userId,{...options.keepTokenId!==undefined&&{exceptTokenId:options.keepTokenId},...options.keepSessionId!==undefined&&{exceptSessionId:options.keepSessionId}})});if(!swept)return{success:false,reason:"invalid-current-password"};const notify=options.notify??true;if(notify!==false&&user.email){const recipient={id:Number(user.id),email:String(user.email),...user.name?{name:String(user.name)}:{}};const send=async()=>{try{if(typeof notify==="function")await notify(recipient);else await sendPasswordChangedNotification(recipient.email)}catch(error){log.error(`[auth] password-changed notification failed: ${error instanceof Error?error.message:String(error)}`)}};if(!enqueueAfterCommit(send))send()}return{success:true,keptTokenId:swept.keptTokenId}}export async function sendPasswordChangedNotification(userEmail){const appName=config.app.name||"Stacks";const supportEmail=config.app.supportEmail||config.email?.from?.address||"";const changedAt=new Date().toLocaleString("en-US",{dateStyle:"full",timeStyle:"short"});try{const{html,text}=await template("password-changed",{subject:`Your ${appName} password has been changed`,variables:{changedAt,supportEmail}});if(!html&&!text){await mail.sendOrFail({to:userEmail,subject:`Your ${appName} password has been changed`,text:`Your ${appName} password was changed on ${changedAt}.${supportEmail?` If this wasn't you, contact ${supportEmail}.`:""}`});return}await mail.sendOrFail({to:userEmail,subject:`Your ${appName} password has been changed`,text,html})}catch(error){console.error("[PasswordReset] Failed to send password changed notification:",error)}}
8
+ `,[stamp,userId]).execute();return rows.length===1&&(rows[0]?.stamp_matches===true||rows[0]?.stamp_matches===1)}async function revokePendingPasswordResets(email){if(typeof email!=="string"||!email)return;try{await db.transaction(async()=>{await deletePasswordResetCredentials(email)})}catch(error){const message=error&&typeof error==="object"&&"message"in error&&typeof error.message==="string"?error.message:String(error);if(/^(?:no such table: (?:main\.)?password_resets|relation "password_resets" does not exist|Table '(?:[^'.]+\.)?password_resets' doesn't exist)$/i.test(message))return;throw error}}export async function revokeAccountCredentials(userId,options={}){if(!Number.isSafeInteger(userId)||userId<=0)throw new TypeError("[auth] revokeAccountCredentials needs a positive integer user id.");if(options.exceptTokenId!==undefined&&(!Number.isSafeInteger(options.exceptTokenId)||options.exceptTokenId<=0))throw new TypeError("[auth] exceptTokenId must be a positive integer.");if(options.tx!==undefined&&!isInTransaction())throw new TypeError("[auth] revokeAccountCredentials was given a tx but is not running inside that transaction.");return db.transaction(async()=>{let ownerQuery=db.primary.selectFrom("users").where("id","=",userId).selectAll();if(getDatabaseDialect()!=="sqlite")ownerQuery=ownerQuery.lockForUpdate();const owner=await ownerQuery.executeTakeFirst();if(!owner)throw new Error("[auth] revokeAccountCredentials: the user does not exist.");let passwordChangedAt=null;const stampValue=sqlDateTime(new Date);if(Object.hasOwn(owner,"password_changed_at")){const stamped=await db.updateTable("users").set({password_changed_at:stampValue}).where("id","=",userId).execute();const changed=mutationCount(stamped);if(changed!==1&&!(changed===0&&getDatabaseDialect()==="mysql"&&await mysqlPasswordStampMatches(userId,stampValue)))throw new Error("[auth] revokeAccountCredentials could not stamp password_changed_at.");passwordChangedAt=parseSqlDateTime(stampValue)}else{log.warn("[auth] password_changed_at column missing - run `buddy migrate`; credentials are revoked without the credential-version stamp")}await revokePendingPasswordResets(owner.email);await revokeTwoFactorChallenges(userId);await revokeMagicLinks(userId);await revokeOAuthSubjectAuthorizationState("users",userId);await revokeTokenPairs(userId,DEFAULT_TOKENABLE_TYPE,options.exceptTokenId);await sessionDestroyAll(userId,options.exceptSessionId!==undefined?{exceptId:options.exceptSessionId}:{});let keptTokenId=null;if(options.exceptTokenId!==undefined&&passwordChangedAt){const rebound=await db.updateTable("oauth_access_tokens").set({created_at:stampValue}).where("id","=",options.exceptTokenId).where("tokenable_id","=",userId).execute();if(mutationCount(rebound)===1){await db.updateTable("oauth_refresh_tokens").set({created_at:stampValue}).where("access_token_id","=",options.exceptTokenId).execute();keptTokenId=options.exceptTokenId}}else if(options.exceptTokenId!==undefined){keptTokenId=options.exceptTokenId}return{passwordChangedAt,keptTokenId}})}export async function changePassword(userId,currentPassword,newPassword,options={}){if(typeof newPassword!=="string"||newPassword.length===0)return{success:false,reason:"invalid-new-password"};const user=await db.primary.selectFrom("users").where("id","=",userId).selectAll().executeTakeFirst();if(!user)return{success:false,reason:"user-not-found"};const storedHash=typeof user.password==="string"?user.password:"";if(typeof currentPassword!=="string"||!storedHash||!await verifyHash(currentPassword,storedHash))return{success:false,reason:"invalid-current-password"};const hashed=await makeHash(newPassword,{algorithm:"bcrypt"});const swept=await withVerifiedPassword(userId,storedHash,async()=>{const updated=await db.updateTable("users").set({password:hashed,...Object.hasOwn(user,"updated_at")?{updated_at:sqlDateTime()}:{}}).where("id","=",userId).execute();if(mutationCount(updated)!==1)throw new Error("[auth] changePassword could not update the password.");return revokeAccountCredentials(userId,{...options.keepTokenId!==undefined&&{exceptTokenId:options.keepTokenId},...options.keepSessionId!==undefined&&{exceptSessionId:options.keepSessionId}})});if(!swept)return{success:false,reason:"invalid-current-password"};const notify=options.notify??true;if(notify!==false&&user.email){const recipient={id:Number(user.id),email:String(user.email),...user.name?{name:String(user.name)}:{}};const send=async()=>{try{if(typeof notify==="function")await notify(recipient);else await sendPasswordChangedNotification(recipient.email)}catch(error){log.error(`[auth] password-changed notification failed: ${error instanceof Error?error.message:String(error)}`)}};if(!enqueueAfterCommit(send))send()}return{success:true,keptTokenId:swept.keptTokenId}}export async function sendPasswordChangedNotification(userEmail){const appName=config.app.name||"Stacks";const supportEmail=config.app.supportEmail||config.email?.from?.address||"";const changedAt=new Date().toLocaleString("en-US",{dateStyle:"full",timeStyle:"short"});try{const{html,text}=await template("password-changed",{subject:`Your ${appName} password has been changed`,variables:{changedAt,supportEmail}});if(!html&&!text){await mail.sendOrFail({tag:"transactional",to:userEmail,subject:`Your ${appName} password has been changed`,text:`Your ${appName} password was changed on ${changedAt}.${supportEmail?` If this wasn't you, contact ${supportEmail}.`:""}`});return}await mail.sendOrFail({tag:"transactional",to:userEmail,subject:`Your ${appName} password has been changed`,text,html})}catch(error){console.error("[PasswordReset] Failed to send password changed notification:",error)}}
@@ -2,4 +2,4 @@ import{randomBytes}from"node:crypto";import{config,feature,overridesReady}from"@
2
2
 
3
3
  This link expires in ${expiresIn}.`:`Reset your password by visiting: ${resetUrl}
4
4
 
5
- This link expires in ${expiresIn}. If you didn't request this, you can safely ignore this email.`}await mail.sendOrFail({to:delivery.email,subject,text,html})}async function verifyToken(token){const result=await db.primary.selectFrom("password_resets").where("email","=",email).select(["token","expires_at","created_at"]).executeTakeFirst();if(!result)return false;if(!isWithinExpiry(result)){await db.deleteFrom("password_resets").where("email","=",email).where("token","=",result.token).execute();return false}const hashedToken=result.token;return await verifyHash(token,hashedToken)}async function resetPassword(token,newPassword){const owner=await findAuthUserRowByEmail(email);if(!owner)return{success:false,message:"Invalid or expired reset token"};const ownerId=Number(owner.id);if(!Number.isSafeInteger(ownerId)||ownerId<=0)return{success:false,message:"Invalid or expired reset token"};const result=await db.transaction(async(rawTrx)=>{const trx=rawTrx;let userQuery=trx.selectFrom("users").where("id","=",ownerId).selectAll();if(getDatabaseDialect()!=="sqlite")userQuery=userQuery.lockForUpdate();const user=await userQuery.executeTakeFirst();if(!user||normalizeAuthEmail(String(user.email??""))!==email)return{success:false,message:"Invalid or expired reset token"};let resetQuery=trx.selectFrom("password_resets").where("email","=",email).select(["token","expires_at","created_at"]);if(getDatabaseDialect()!=="sqlite")resetQuery=resetQuery.lockForUpdate();const resetRecord=await resetQuery.executeTakeFirst();if(!resetRecord){return{success:false,message:"Invalid or expired reset token"}}if(!isWithinExpiry(resetRecord)){await trx.deleteFrom("password_resets").where("email","=",email).execute();return{success:false,message:"This password reset link has expired. Please request a new one."}}const hashedToken=resetRecord.token;const isValid=await verifyHash(token,hashedToken);if(!isValid){return{success:false,message:"Invalid or expired reset token"}}const hashedPassword=await makeHash(newPassword,{algorithm:"bcrypt"});if(!isWithinExpiry(resetRecord))return{success:false,message:"Invalid or expired reset token"};const updated=await trx.updateTable("users").set({password:hashedPassword}).where("id","=",user.id).execute();if(mutationCount(updated)!==1)throw new Error("Password reset could not update its owner");const consumed=await trx.deleteFrom("password_resets").where("email","=",email).where("token","=",hashedToken).execute();if(mutationCount(consumed)!==1)throw new Error("Password reset token could not be consumed");await revokeAccountCredentials(Number(user.id));return{success:true}});if(result.success){const notify=()=>sendPasswordChangedNotification(email).catch((err)=>{console.error("[PasswordReset] Failed to send notification:",err)});if(!enqueueAfterCommit(notify))notify();return{success:true}}return result}return{sendEmail,verifyToken,resetPassword}}let warnedDefaultResetPage=false;async function warnIfDefaultResetPageMissing(){if(warnedDefaultResetPage)return;warnedDefaultResetPage=true;try{await overridesReady;if(mountedDefaultRouteBundles(feature).has("auth"))return}catch{return}log.warn("[PasswordReset] Reset links point at the default /password/reset/{token} page, which needs the auth route bundle, and it is not mounted (it mounts with the dashboard, or with STACKS_DEFAULT_ROUTES=auth). Set config.auth.passwordReset.url to your own reset page, or mount the bundle.")}
5
+ This link expires in ${expiresIn}. If you didn't request this, you can safely ignore this email.`}await mail.sendOrFail({tag:"transactional",to:delivery.email,subject,text,html})}async function verifyToken(token){const result=await db.primary.selectFrom("password_resets").where("email","=",email).select(["token","expires_at","created_at"]).executeTakeFirst();if(!result)return false;if(!isWithinExpiry(result)){await db.deleteFrom("password_resets").where("email","=",email).where("token","=",result.token).execute();return false}const hashedToken=result.token;return await verifyHash(token,hashedToken)}async function resetPassword(token,newPassword){const owner=await findAuthUserRowByEmail(email);if(!owner)return{success:false,message:"Invalid or expired reset token"};const ownerId=Number(owner.id);if(!Number.isSafeInteger(ownerId)||ownerId<=0)return{success:false,message:"Invalid or expired reset token"};const result=await db.transaction(async(rawTrx)=>{const trx=rawTrx;let userQuery=trx.selectFrom("users").where("id","=",ownerId).selectAll();if(getDatabaseDialect()!=="sqlite")userQuery=userQuery.lockForUpdate();const user=await userQuery.executeTakeFirst();if(!user||normalizeAuthEmail(String(user.email??""))!==email)return{success:false,message:"Invalid or expired reset token"};let resetQuery=trx.selectFrom("password_resets").where("email","=",email).select(["token","expires_at","created_at"]);if(getDatabaseDialect()!=="sqlite")resetQuery=resetQuery.lockForUpdate();const resetRecord=await resetQuery.executeTakeFirst();if(!resetRecord){return{success:false,message:"Invalid or expired reset token"}}if(!isWithinExpiry(resetRecord)){await trx.deleteFrom("password_resets").where("email","=",email).execute();return{success:false,message:"This password reset link has expired. Please request a new one."}}const hashedToken=resetRecord.token;const isValid=await verifyHash(token,hashedToken);if(!isValid){return{success:false,message:"Invalid or expired reset token"}}const hashedPassword=await makeHash(newPassword,{algorithm:"bcrypt"});if(!isWithinExpiry(resetRecord))return{success:false,message:"Invalid or expired reset token"};const updated=await trx.updateTable("users").set({password:hashedPassword}).where("id","=",user.id).execute();if(mutationCount(updated)!==1)throw new Error("Password reset could not update its owner");const consumed=await trx.deleteFrom("password_resets").where("email","=",email).where("token","=",hashedToken).execute();if(mutationCount(consumed)!==1)throw new Error("Password reset token could not be consumed");await revokeAccountCredentials(Number(user.id));return{success:true}});if(result.success){const notify=()=>sendPasswordChangedNotification(email).catch((err)=>{console.error("[PasswordReset] Failed to send notification:",err)});if(!enqueueAfterCommit(notify))notify();return{success:true}}return result}return{sendEmail,verifyToken,resetPassword}}let warnedDefaultResetPage=false;async function warnIfDefaultResetPageMissing(){if(warnedDefaultResetPage)return;warnedDefaultResetPage=true;try{await overridesReady;if(mountedDefaultRouteBundles(feature).has("auth"))return}catch{return}log.warn("[PasswordReset] Reset links point at the default /password/reset/{token} page, which needs the auth route bundle, and it is not mounted (it mounts with the dashboard, or with STACKS_DEFAULT_ROUTES=auth). Set config.auth.passwordReset.url to your own reset page, or mount the bundle.")}
@@ -53,7 +53,8 @@ export declare function sessionLogout(sessionId: string): Promise<void>;
53
53
  *
54
54
  * Like `sessionLogout`, real failures propagate (fail loud): a reset
55
55
  * that reports success while the attacker's session lives would be a
56
- * lie. An absent legacy `sessions` table or an unapplied browser-session
56
+ * lie. An absent legacy `sessions` table, an application's own table of
57
+ * that name (one with no `user_id`), or an unapplied browser-session
57
58
  * migration has no credential to revoke. A missing trigger dependency is
58
59
  * still a real failure and rolls back both credential families.
59
60
  */
@@ -1 +1 @@
1
- import{HttpError}from"@stacksjs/error-handling";import{log}from"@stacksjs/logging";import{User}from"@stacksjs/orm";import{verifyHash}from"@stacksjs/security";import{config}from"@stacksjs/config";import{db,getDatabaseDialect,parseSqlDateTime,sqlDateTime}from"@stacksjs/database/runtime";import{clientAddress,getCurrentRequest}from"@stacksjs/router";import{DUMMY_BCRYPT_HASH}from"./internal-constants";import{findAuthUserByEmail,normalizeAuthEmail}from"./credential-user";import{RateLimiter}from"./rate-limiter";import{withVerifiedPassword}from"./credential-version";import{schedulePasswordRehash}from"./password-rehash";import{sessionCredentialIdentifier}from"./session-credential";function sessionTable(identifier){return identifier.startsWith("bs1:")?"auth_browser_sessions":"sessions"}function generateSessionId(){const bytes=crypto.getRandomValues(new Uint8Array(32));return Array.from(bytes,(b)=>b.toString(16).padStart(2,"0")).join("")}export function readRequestFingerprint(override){if(override){return{ip:override.ip??null,userAgent:override.userAgent??null}}const req=getCurrentRequest();if(!req)return{ip:null,userAgent:null,inRequest:false};const headers=req.headers;const ip=clientAddress(req);const userAgent=headers?.get?.("user-agent")||headers?.get?.("User-Agent")||null;return{ip,userAgent,inRequest:true}}export function fingerprintMismatch(enforce,stored,current){if(!enforce)return false;const enforceIp=enforce===true||!!enforce.ip;const enforceUa=enforce===true||!!enforce.userAgent;if(!enforceIp&&!enforceUa)return false;if(enforceIp&&current.ip!=null&&stored.ip!=null&&String(stored.ip)!==current.ip)return true;if(enforceUa&&stored.userAgent!=null&&current.userAgent!=null&&String(stored.userAgent)!==current.userAgent)return true;if(enforceUa&&stored.userAgent!=null&&current.userAgent==null&&current.inRequest===true)return true;return false}function sessionFingerprintRejected(session){return fingerprintMismatch(config.auth?.session?.enforceFingerprint,{ip:session.ip_address,userAgent:session.user_agent},readRequestFingerprint())}export async function sessionLogin(email,password,fingerprint){const normalizedEmail=normalizeAuthEmail(email||"");const isRateLimited=await RateLimiter.isRateLimited(normalizedEmail);const user=await findAuthUserByEmail(normalizedEmail);const hashToVerify=user?.password||DUMMY_BCRYPT_HASH;const isValid=await verifyHash(password,hashToVerify);if(isRateLimited)throw new HttpError(429,"Too many login attempts. Please try again later.");if(!isValid||!user){await RateLimiter.recordFailedAttempt(normalizedEmail);throw new HttpError(401,"Invalid credentials")}await RateLimiter.resetAttempts(normalizedEmail);const sessionId=generateSessionId();const expiresAt=new Date(Date.now()+24*60*60*1000);if(getDatabaseDialect()==="mysql")expiresAt.setUTCMilliseconds(0);const{ip,userAgent}=readRequestFingerprint(fingerprint);let persisted;try{persisted=await withVerifiedPassword(user.id,hashToVerify,async()=>{await db.insertInto("sessions").values({id:sessionId,user_id:user.id,ip_address:ip,user_agent:userAgent,payload:"{}",last_activity:Math.floor(Date.now()/1000),expires_at:sqlDateTime(expiresAt)}).execute();const stored=await db.primary.selectFrom("sessions").where("id","=",sessionId).select(["user_id","expires_at"]).executeTakeFirst();if(!stored||String(stored.user_id)!==String(user.id)||parseSqlDateTime(stored.expires_at)?.getTime()!==expiresAt.getTime()||(parseSqlDateTime(stored.expires_at)?.getTime()??0)<=Date.now())throw new Error("Session insert did not persist a usable credential for the verified user.");return true})}catch(err){log.error(`[auth] Session persistence failed for user#${user.id}: ${err.message}`);throw new HttpError(500,"Session could not be created. Ensure the `sessions` table exists (run `./buddy migrate`).")}if(!persisted)throw new HttpError(401,"Invalid credentials");schedulePasswordRehash(user.id,password,hashToVerify);log.debug(`[auth] Session created for user#${user.id}`);return{user,sessionId}}export async function sessionLogout(sessionId){const identifier=sessionCredentialIdentifier(sessionId);if(!identifier)return;sessionId=identifier;await db.transaction(async()=>{let observed=db.primary.selectFrom(sessionTable(sessionId)).where("id","=",sessionId).select("id");if(getDatabaseDialect()!=="sqlite")observed=observed.lockForUpdate();const current=await observed.executeTakeFirst();if(!current||String(current.id)!==sessionId)return;await db.deleteFrom(sessionTable(sessionId)).where("id","=",sessionId).execute();const remaining=await db.primary.selectFrom(sessionTable(sessionId)).where("id","=",sessionId).select("id").executeTakeFirst();if(remaining)throw new HttpError(500,"Session could not be destroyed.")});log.debug("[auth] Session destroyed")}export async function sessionDestroyAll(userId,options={}){const exceptId=options.exceptId?.startsWith("bs1_")?sessionCredentialIdentifier(options.exceptId):options.exceptId;if(options.exceptId?.startsWith("bs1_")&&!exceptId)throw new TypeError("[auth] Invalid browser session credential to preserve.");await db.transaction(async()=>{for(const table of["sessions","auth_browser_sessions"]){try{await db.transaction(async()=>{let removal=db.deleteFrom(table).where("user_id","=",userId);if(exceptId!==undefined)removal=removal.where("id","!=",exceptId);await removal.execute();let check=db.primary.selectFrom(table).where("user_id","=",userId);if(exceptId!==undefined)check=check.where("id","!=",exceptId);if(await check.select("id").executeTakeFirst())throw new HttpError(500,"Sessions could not be destroyed.")})}catch(error){const message=error&&typeof error==="object"&&"message"in error?String(error.message):String(error);const missing=/^(?:no such table: (?:main\.)?(sessions|auth_browser_sessions)|relation "(sessions|auth_browser_sessions)" does not exist|Table '(?:[^'.]+\.)?(sessions|auth_browser_sessions)' doesn't exist)$/i.exec(message);if(!missing?.slice(1).some((name)=>name?.toLowerCase()===table))throw error}}})}async function deleteObservedExpiredSession(sessionId,expiresAt){const cleanup=db.deleteFrom(sessionTable(sessionId)).where("id","=",sessionId);await(expiresAt==null?cleanup.whereNull("expires_at"):cleanup.where("expires_at","=",expiresAt)).execute()}async function deleteObservedOrphanedSession(sessionId,userId,expiresAt){let cleanup=db.deleteFrom(sessionTable(sessionId)).where("id","=",sessionId).where("user_id","=",userId);cleanup=expiresAt==null?cleanup.whereNull("expires_at"):cleanup.where("expires_at","=",expiresAt);await cleanup.execute()}async function sessionOwnerExists(userId,lock=false){let query=db.primary.selectFrom("users").where("id","=",userId).select("id");if(lock&&getDatabaseDialect()!=="sqlite")query=query.lockForUpdate();const owner=await query.executeTakeFirst();return owner!==undefined}function sessionIdleTimeoutExceeded(lastActivity){const idleMs=config.auth?.idleTimeout??0;if(idleMs<=0)return false;const seconds=Number(lastActivity);if(!Number.isFinite(seconds)||seconds<=0)return true;return Date.now()-seconds*1000>idleMs}async function deleteObservedIdleSession(sessionId,userId,expiresAt,lastActivity){let cleanup=db.deleteFrom(sessionTable(sessionId)).where("id","=",sessionId).where("user_id","=",userId);cleanup=expiresAt==null?cleanup.whereNull("expires_at"):cleanup.where("expires_at","=",expiresAt);cleanup=lastActivity==null?cleanup.whereNull("last_activity"):cleanup.where("last_activity","=",lastActivity);await cleanup.execute()}async function touchSessionActivity(sessionId,expiresAt,lastActivity){if((config.auth?.idleTimeout??0)<=0&&!sessionId.startsWith("bs1:"))return;let touch=db.updateTable(sessionTable(sessionId)).set({last_activity:Math.floor(Date.now()/1000)}).where("id","=",sessionId);touch=expiresAt==null?touch.whereNull("expires_at"):touch.where("expires_at","=",expiresAt);touch=lastActivity==null?touch.whereNull("last_activity"):touch.where("last_activity","=",lastActivity);await touch.execute()}export async function sessionUser(sessionId){const identifier=sessionCredentialIdentifier(sessionId);if(!identifier)return;sessionId=identifier;try{const query=db.primary.selectFrom(sessionTable(sessionId)).where("id","=",sessionId);const session=config.auth?.session?.enforceFingerprint?await query.select(["id","user_id","expires_at","last_activity","ip_address","user_agent"]).executeTakeFirst():await query.select(["id","user_id","expires_at","last_activity"]).executeTakeFirst();if(!session||String(session.id)!==sessionId)return;const expiresAt=parseSqlDateTime(session.expires_at)?.getTime()??0;if(Date.now()>=expiresAt){await deleteObservedExpiredSession(sessionId,session.expires_at);return}if(sessionIdleTimeoutExceeded(session.last_activity)){await deleteObservedIdleSession(sessionId,session.user_id,session.expires_at,session.last_activity);return}if(sessionFingerprintRejected(session)){log.warn(`[auth] Session fingerprint mismatch - rejecting request (possible hijack, session left intact)`);return}const userId=session.user_id;if(!await sessionOwnerExists(userId)){await deleteObservedOrphanedSession(sessionId,userId,session.expires_at);return}await touchSessionActivity(sessionId,session.expires_at,session.last_activity);return await User.find(userId)}catch{return}}export async function sessionCheck(sessionId){const identifier=sessionCredentialIdentifier(sessionId);if(!identifier)return false;sessionId=identifier;try{const query=db.primary.selectFrom(sessionTable(sessionId)).where("id","=",sessionId);const session=config.auth?.session?.enforceFingerprint?await query.select(["id","user_id","expires_at","last_activity","ip_address","user_agent"]).executeTakeFirst():await query.select(["id","user_id","expires_at","last_activity"]).executeTakeFirst();if(!session||String(session.id)!==sessionId)return false;const expiresAt=parseSqlDateTime(session.expires_at)?.getTime()??0;if(Date.now()>=expiresAt){await deleteObservedExpiredSession(sessionId,session.expires_at);return false}if(sessionIdleTimeoutExceeded(session.last_activity)){await deleteObservedIdleSession(sessionId,session.user_id,session.expires_at,session.last_activity);return false}if(sessionFingerprintRejected(session))return false;const userId=session.user_id;if(!await sessionOwnerExists(userId)){await deleteObservedOrphanedSession(sessionId,userId,session.expires_at);return false}await touchSessionActivity(sessionId,session.expires_at,session.last_activity);return true}catch{return false}}export async function sessionRefresh(sessionId,ttlMs=24*60*60*1000){const identifier=sessionCredentialIdentifier(sessionId);if(!identifier)return false;sessionId=identifier;if(!Number.isFinite(ttlMs)||ttlMs<=0)return false;try{const query=db.primary.selectFrom(sessionTable(sessionId)).where("id","=",sessionId);const session=config.auth?.session?.enforceFingerprint?await query.select(["id","user_id","expires_at","last_activity","ip_address","user_agent"]).executeTakeFirst():await query.select(["id","user_id","expires_at","last_activity"]).executeTakeFirst();if(!session||String(session.id)!==sessionId)return false;const expiresAt=parseSqlDateTime(session.expires_at)?.getTime()??0;if(Date.now()>=expiresAt){await deleteObservedExpiredSession(sessionId,session.expires_at);return false}if(sessionIdleTimeoutExceeded(session.last_activity)){await deleteObservedIdleSession(sessionId,session.user_id,session.expires_at,session.last_activity);return false}if(sessionFingerprintRejected(session))return false;return await db.transaction(async()=>{const mysql=getDatabaseDialect()==="mysql";if(mysql){const current=await db.primary.selectFrom(sessionTable(sessionId)).where("id","=",sessionId).where("expires_at","=",session.expires_at).select("id").lockForUpdate().executeTakeFirst();if(!current||String(current.id)!==sessionId)return false}const userId=session.user_id;if(!await sessionOwnerExists(userId,true)){await deleteObservedOrphanedSession(sessionId,userId,session.expires_at);return false}const newExpiry=new Date(Date.now()+ttlMs);if(mysql)newExpiry.setUTCMilliseconds(0);if(!Number.isFinite(newExpiry.getTime())||newExpiry.getTime()<=Date.now())return false;const lastActivity=Math.floor(Date.now()/1000);const result=await db.updateTable(sessionTable(sessionId)).set({expires_at:sqlDateTime(newExpiry),last_activity:lastActivity}).where("id","=",sessionId).where("expires_at","=",session.expires_at).where("user_id","=",session.user_id).returning("id").executeTakeFirst();if(Date.now()>=expiresAt||Date.now()>=newExpiry.getTime())throw new Error("[auth] Session expired during renewal.");if(!result)return false;let storedQuery=db.primary.selectFrom(sessionTable(sessionId)).where("id","=",sessionId).select(["id","user_id","expires_at","last_activity"]);if(mysql)storedQuery=storedQuery.lockForUpdate();const stored=await storedQuery.executeTakeFirst();if(!stored||String(stored.id)!==sessionId||String(stored.user_id)!==String(session.user_id)||parseSqlDateTime(stored.expires_at)?.getTime()!==newExpiry.getTime()||Number(stored.last_activity)!==lastActivity||Date.now()>=Math.min(expiresAt,newExpiry.getTime()))throw new Error("[auth] Session renewal did not persist the requested credential.");if(!await sessionOwnerExists(userId,true))throw new Error("[auth] Session owner disappeared during renewal.");return true})}catch{return false}}export const SessionAuth={login:sessionLogin,logout:sessionLogout,destroyAll:sessionDestroyAll,user:sessionUser,check:sessionCheck,refresh:sessionRefresh};
1
+ import{HttpError}from"@stacksjs/error-handling";import{log}from"@stacksjs/logging";import{User}from"@stacksjs/orm";import{verifyHash}from"@stacksjs/security";import{config}from"@stacksjs/config";import{db,getDatabaseDialect,parseSqlDateTime,sqlDateTime,tableHasColumn}from"@stacksjs/database/runtime";import{clientAddress,getCurrentRequest}from"@stacksjs/router";import{DUMMY_BCRYPT_HASH}from"./internal-constants";import{findAuthUserByEmail,normalizeAuthEmail}from"./credential-user";import{RateLimiter}from"./rate-limiter";import{withVerifiedPassword}from"./credential-version";import{schedulePasswordRehash}from"./password-rehash";import{sessionCredentialIdentifier}from"./session-credential";function sessionTable(identifier){return identifier.startsWith("bs1:")?"auth_browser_sessions":"sessions"}function generateSessionId(){const bytes=crypto.getRandomValues(new Uint8Array(32));return Array.from(bytes,(b)=>b.toString(16).padStart(2,"0")).join("")}export function readRequestFingerprint(override){if(override){return{ip:override.ip??null,userAgent:override.userAgent??null}}const req=getCurrentRequest();if(!req)return{ip:null,userAgent:null,inRequest:false};const headers=req.headers;const ip=clientAddress(req);const userAgent=headers?.get?.("user-agent")||headers?.get?.("User-Agent")||null;return{ip,userAgent,inRequest:true}}export function fingerprintMismatch(enforce,stored,current){if(!enforce)return false;const enforceIp=enforce===true||!!enforce.ip;const enforceUa=enforce===true||!!enforce.userAgent;if(!enforceIp&&!enforceUa)return false;if(enforceIp&&current.ip!=null&&stored.ip!=null&&String(stored.ip)!==current.ip)return true;if(enforceUa&&stored.userAgent!=null&&current.userAgent!=null&&String(stored.userAgent)!==current.userAgent)return true;if(enforceUa&&stored.userAgent!=null&&current.userAgent==null&&current.inRequest===true)return true;return false}function sessionFingerprintRejected(session){return fingerprintMismatch(config.auth?.session?.enforceFingerprint,{ip:session.ip_address,userAgent:session.user_agent},readRequestFingerprint())}export async function sessionLogin(email,password,fingerprint){const normalizedEmail=normalizeAuthEmail(email||"");const isRateLimited=await RateLimiter.isRateLimited(normalizedEmail);const user=await findAuthUserByEmail(normalizedEmail);const hashToVerify=user?.password||DUMMY_BCRYPT_HASH;const isValid=await verifyHash(password,hashToVerify);if(isRateLimited)throw new HttpError(429,"Too many login attempts. Please try again later.");if(!isValid||!user){await RateLimiter.recordFailedAttempt(normalizedEmail);throw new HttpError(401,"Invalid credentials")}await RateLimiter.resetAttempts(normalizedEmail);const sessionId=generateSessionId();const expiresAt=new Date(Date.now()+24*60*60*1000);if(getDatabaseDialect()==="mysql")expiresAt.setUTCMilliseconds(0);const{ip,userAgent}=readRequestFingerprint(fingerprint);let persisted;try{persisted=await withVerifiedPassword(user.id,hashToVerify,async()=>{await db.insertInto("sessions").values({id:sessionId,user_id:user.id,ip_address:ip,user_agent:userAgent,payload:"{}",last_activity:Math.floor(Date.now()/1000),expires_at:sqlDateTime(expiresAt)}).execute();const stored=await db.primary.selectFrom("sessions").where("id","=",sessionId).select(["user_id","expires_at"]).executeTakeFirst();if(!stored||String(stored.user_id)!==String(user.id)||parseSqlDateTime(stored.expires_at)?.getTime()!==expiresAt.getTime()||(parseSqlDateTime(stored.expires_at)?.getTime()??0)<=Date.now())throw new Error("Session insert did not persist a usable credential for the verified user.");return true})}catch(err){log.error(`[auth] Session persistence failed for user#${user.id}: ${err.message}`);throw new HttpError(500,"Session could not be created. Ensure the `sessions` table exists (run `./buddy migrate`).")}if(!persisted)throw new HttpError(401,"Invalid credentials");schedulePasswordRehash(user.id,password,hashToVerify);log.debug(`[auth] Session created for user#${user.id}`);return{user,sessionId}}export async function sessionLogout(sessionId){const identifier=sessionCredentialIdentifier(sessionId);if(!identifier)return;sessionId=identifier;await db.transaction(async()=>{let observed=db.primary.selectFrom(sessionTable(sessionId)).where("id","=",sessionId).select("id");if(getDatabaseDialect()!=="sqlite")observed=observed.lockForUpdate();const current=await observed.executeTakeFirst();if(!current||String(current.id)!==sessionId)return;await db.deleteFrom(sessionTable(sessionId)).where("id","=",sessionId).execute();const remaining=await db.primary.selectFrom(sessionTable(sessionId)).where("id","=",sessionId).select("id").executeTakeFirst();if(remaining)throw new HttpError(500,"Session could not be destroyed.")});log.debug("[auth] Session destroyed")}export async function sessionDestroyAll(userId,options={}){const exceptId=options.exceptId?.startsWith("bs1_")?sessionCredentialIdentifier(options.exceptId):options.exceptId;if(options.exceptId?.startsWith("bs1_")&&!exceptId)throw new TypeError("[auth] Invalid browser session credential to preserve.");await db.transaction(async()=>{for(const table of["sessions","auth_browser_sessions"]){if(table==="sessions"&&!await tableHasColumn("sessions","user_id"))continue;try{await db.transaction(async()=>{let removal=db.deleteFrom(table).where("user_id","=",userId);if(exceptId!==undefined)removal=removal.where("id","!=",exceptId);await removal.execute();let check=db.primary.selectFrom(table).where("user_id","=",userId);if(exceptId!==undefined)check=check.where("id","!=",exceptId);if(await check.select("id").executeTakeFirst())throw new HttpError(500,"Sessions could not be destroyed.")})}catch(error){const message=error&&typeof error==="object"&&"message"in error?String(error.message):String(error);const missing=/^(?:no such table: (?:main\.)?(sessions|auth_browser_sessions)|relation "(sessions|auth_browser_sessions)" does not exist|Table '(?:[^'.]+\.)?(sessions|auth_browser_sessions)' doesn't exist)$/i.exec(message);if(!missing?.slice(1).some((name)=>name?.toLowerCase()===table))throw error}}})}async function deleteObservedExpiredSession(sessionId,expiresAt){const cleanup=db.deleteFrom(sessionTable(sessionId)).where("id","=",sessionId);await(expiresAt==null?cleanup.whereNull("expires_at"):cleanup.where("expires_at","=",expiresAt)).execute()}async function deleteObservedOrphanedSession(sessionId,userId,expiresAt){let cleanup=db.deleteFrom(sessionTable(sessionId)).where("id","=",sessionId).where("user_id","=",userId);cleanup=expiresAt==null?cleanup.whereNull("expires_at"):cleanup.where("expires_at","=",expiresAt);await cleanup.execute()}async function sessionOwnerExists(userId,lock=false){let query=db.primary.selectFrom("users").where("id","=",userId).select("id");if(lock&&getDatabaseDialect()!=="sqlite")query=query.lockForUpdate();const owner=await query.executeTakeFirst();return owner!==undefined}function sessionIdleTimeoutExceeded(lastActivity){const idleMs=config.auth?.idleTimeout??0;if(idleMs<=0)return false;const seconds=Number(lastActivity);if(!Number.isFinite(seconds)||seconds<=0)return true;return Date.now()-seconds*1000>idleMs}async function deleteObservedIdleSession(sessionId,userId,expiresAt,lastActivity){let cleanup=db.deleteFrom(sessionTable(sessionId)).where("id","=",sessionId).where("user_id","=",userId);cleanup=expiresAt==null?cleanup.whereNull("expires_at"):cleanup.where("expires_at","=",expiresAt);cleanup=lastActivity==null?cleanup.whereNull("last_activity"):cleanup.where("last_activity","=",lastActivity);await cleanup.execute()}async function touchSessionActivity(sessionId,expiresAt,lastActivity){if((config.auth?.idleTimeout??0)<=0&&!sessionId.startsWith("bs1:"))return;let touch=db.updateTable(sessionTable(sessionId)).set({last_activity:Math.floor(Date.now()/1000)}).where("id","=",sessionId);touch=expiresAt==null?touch.whereNull("expires_at"):touch.where("expires_at","=",expiresAt);touch=lastActivity==null?touch.whereNull("last_activity"):touch.where("last_activity","=",lastActivity);await touch.execute()}export async function sessionUser(sessionId){const identifier=sessionCredentialIdentifier(sessionId);if(!identifier)return;sessionId=identifier;try{const query=db.primary.selectFrom(sessionTable(sessionId)).where("id","=",sessionId);const session=config.auth?.session?.enforceFingerprint?await query.select(["id","user_id","expires_at","last_activity","ip_address","user_agent"]).executeTakeFirst():await query.select(["id","user_id","expires_at","last_activity"]).executeTakeFirst();if(!session||String(session.id)!==sessionId)return;const expiresAt=parseSqlDateTime(session.expires_at)?.getTime()??0;if(Date.now()>=expiresAt){await deleteObservedExpiredSession(sessionId,session.expires_at);return}if(sessionIdleTimeoutExceeded(session.last_activity)){await deleteObservedIdleSession(sessionId,session.user_id,session.expires_at,session.last_activity);return}if(sessionFingerprintRejected(session)){log.warn(`[auth] Session fingerprint mismatch - rejecting request (possible hijack, session left intact)`);return}const userId=session.user_id;if(!await sessionOwnerExists(userId)){await deleteObservedOrphanedSession(sessionId,userId,session.expires_at);return}await touchSessionActivity(sessionId,session.expires_at,session.last_activity);return await User.find(userId)}catch{return}}export async function sessionCheck(sessionId){const identifier=sessionCredentialIdentifier(sessionId);if(!identifier)return false;sessionId=identifier;try{const query=db.primary.selectFrom(sessionTable(sessionId)).where("id","=",sessionId);const session=config.auth?.session?.enforceFingerprint?await query.select(["id","user_id","expires_at","last_activity","ip_address","user_agent"]).executeTakeFirst():await query.select(["id","user_id","expires_at","last_activity"]).executeTakeFirst();if(!session||String(session.id)!==sessionId)return false;const expiresAt=parseSqlDateTime(session.expires_at)?.getTime()??0;if(Date.now()>=expiresAt){await deleteObservedExpiredSession(sessionId,session.expires_at);return false}if(sessionIdleTimeoutExceeded(session.last_activity)){await deleteObservedIdleSession(sessionId,session.user_id,session.expires_at,session.last_activity);return false}if(sessionFingerprintRejected(session))return false;const userId=session.user_id;if(!await sessionOwnerExists(userId)){await deleteObservedOrphanedSession(sessionId,userId,session.expires_at);return false}await touchSessionActivity(sessionId,session.expires_at,session.last_activity);return true}catch{return false}}export async function sessionRefresh(sessionId,ttlMs=24*60*60*1000){const identifier=sessionCredentialIdentifier(sessionId);if(!identifier)return false;sessionId=identifier;if(!Number.isFinite(ttlMs)||ttlMs<=0)return false;try{const query=db.primary.selectFrom(sessionTable(sessionId)).where("id","=",sessionId);const session=config.auth?.session?.enforceFingerprint?await query.select(["id","user_id","expires_at","last_activity","ip_address","user_agent"]).executeTakeFirst():await query.select(["id","user_id","expires_at","last_activity"]).executeTakeFirst();if(!session||String(session.id)!==sessionId)return false;const expiresAt=parseSqlDateTime(session.expires_at)?.getTime()??0;if(Date.now()>=expiresAt){await deleteObservedExpiredSession(sessionId,session.expires_at);return false}if(sessionIdleTimeoutExceeded(session.last_activity)){await deleteObservedIdleSession(sessionId,session.user_id,session.expires_at,session.last_activity);return false}if(sessionFingerprintRejected(session))return false;return await db.transaction(async()=>{const mysql=getDatabaseDialect()==="mysql";if(mysql){const current=await db.primary.selectFrom(sessionTable(sessionId)).where("id","=",sessionId).where("expires_at","=",session.expires_at).select("id").lockForUpdate().executeTakeFirst();if(!current||String(current.id)!==sessionId)return false}const userId=session.user_id;if(!await sessionOwnerExists(userId,true)){await deleteObservedOrphanedSession(sessionId,userId,session.expires_at);return false}const newExpiry=new Date(Date.now()+ttlMs);if(mysql)newExpiry.setUTCMilliseconds(0);if(!Number.isFinite(newExpiry.getTime())||newExpiry.getTime()<=Date.now())return false;const lastActivity=Math.floor(Date.now()/1000);const result=await db.updateTable(sessionTable(sessionId)).set({expires_at:sqlDateTime(newExpiry),last_activity:lastActivity}).where("id","=",sessionId).where("expires_at","=",session.expires_at).where("user_id","=",session.user_id).returning("id").executeTakeFirst();if(Date.now()>=expiresAt||Date.now()>=newExpiry.getTime())throw new Error("[auth] Session expired during renewal.");if(!result)return false;let storedQuery=db.primary.selectFrom(sessionTable(sessionId)).where("id","=",sessionId).select(["id","user_id","expires_at","last_activity"]);if(mysql)storedQuery=storedQuery.lockForUpdate();const stored=await storedQuery.executeTakeFirst();if(!stored||String(stored.id)!==sessionId||String(stored.user_id)!==String(session.user_id)||parseSqlDateTime(stored.expires_at)?.getTime()!==newExpiry.getTime()||Number(stored.last_activity)!==lastActivity||Date.now()>=Math.min(expiresAt,newExpiry.getTime()))throw new Error("[auth] Session renewal did not persist the requested credential.");if(!await sessionOwnerExists(userId,true))throw new Error("[auth] Session owner disappeared during renewal.");return true})}catch{return false}}export const SessionAuth={login:sessionLogin,logout:sessionLogout,destroyAll:sessionDestroyAll,user:sessionUser,check:sessionCheck,refresh:sessionRefresh};
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@stacksjs/auth",
3
3
  "type": "module",
4
4
  "sideEffects": false,
5
- "version": "0.75.599",
5
+ "version": "0.75.602",
6
6
  "description": "A more simplistic way to authenticate.",
7
7
  "author": "Chris Breuer",
8
8
  "contributors": [
@@ -59,19 +59,19 @@
59
59
  },
60
60
  "dependencies": {
61
61
  "@stacksjs/bun-router": "^0.1.24",
62
- "@stacksjs/cache": "0.75.599",
63
- "@stacksjs/config": "0.75.599",
64
- "@stacksjs/database": "0.75.599",
65
- "@stacksjs/email": "0.75.599",
66
- "@stacksjs/env": "0.75.599",
67
- "@stacksjs/error-handling": "0.75.599",
68
- "@stacksjs/logging": "0.75.599",
69
- "@stacksjs/orm": "0.75.599",
70
- "@stacksjs/path": "0.75.599",
71
- "@stacksjs/router": "0.75.599",
72
- "@stacksjs/security": "0.75.599",
73
- "@stacksjs/socials": "0.75.599",
74
- "@stacksjs/storage": "0.75.599",
62
+ "@stacksjs/cache": "0.75.602",
63
+ "@stacksjs/config": "0.75.602",
64
+ "@stacksjs/database": "0.75.602",
65
+ "@stacksjs/email": "0.75.602",
66
+ "@stacksjs/env": "0.75.602",
67
+ "@stacksjs/error-handling": "0.75.602",
68
+ "@stacksjs/logging": "0.75.602",
69
+ "@stacksjs/orm": "0.75.602",
70
+ "@stacksjs/path": "0.75.602",
71
+ "@stacksjs/router": "0.75.602",
72
+ "@stacksjs/security": "0.75.602",
73
+ "@stacksjs/socials": "0.75.602",
74
+ "@stacksjs/storage": "0.75.602",
75
75
  "@stacksjs/ts-auth": "^0.4.7",
76
76
  "ts-qr-codes": "^0.1.8",
77
77
  "oauth4webapi": "^3.8.8",