@stacksjs/auth 0.75.598 → 0.75.600

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.
@@ -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.598",
5
+ "version": "0.75.600",
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.598",
63
- "@stacksjs/config": "0.75.598",
64
- "@stacksjs/database": "0.75.598",
65
- "@stacksjs/email": "0.75.598",
66
- "@stacksjs/env": "0.75.598",
67
- "@stacksjs/error-handling": "0.75.598",
68
- "@stacksjs/logging": "0.75.598",
69
- "@stacksjs/orm": "0.75.598",
70
- "@stacksjs/path": "0.75.598",
71
- "@stacksjs/router": "0.75.598",
72
- "@stacksjs/security": "0.75.598",
73
- "@stacksjs/socials": "0.75.598",
74
- "@stacksjs/storage": "0.75.598",
62
+ "@stacksjs/cache": "0.75.600",
63
+ "@stacksjs/config": "0.75.600",
64
+ "@stacksjs/database": "0.75.600",
65
+ "@stacksjs/email": "0.75.600",
66
+ "@stacksjs/env": "0.75.600",
67
+ "@stacksjs/error-handling": "0.75.600",
68
+ "@stacksjs/logging": "0.75.600",
69
+ "@stacksjs/orm": "0.75.600",
70
+ "@stacksjs/path": "0.75.600",
71
+ "@stacksjs/router": "0.75.600",
72
+ "@stacksjs/security": "0.75.600",
73
+ "@stacksjs/socials": "0.75.600",
74
+ "@stacksjs/storage": "0.75.600",
75
75
  "@stacksjs/ts-auth": "^0.4.7",
76
76
  "ts-qr-codes": "^0.1.8",
77
77
  "oauth4webapi": "^3.8.8",