@sqrzro/server 4.0.0-alpha.10 → 4.0.0-alpha.11

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,2 +1,2 @@
1
- import {a,g,e as e$1,h as h$1,b as b$1,i,d,c as c$2,f as f$1}from'../chunk-UQQMJZWP.js';export{l as ensureSessionUser,k as getSessionUser,j as validateSession}from'../chunk-UQQMJZWP.js';import {a as a$1}from'../chunk-AGS5PPG2.js';import'../chunk-37TYQL5Y.js';import {c as c$1}from'../chunk-XSJ4OEIH.js';import {e,f}from'../chunk-JI2U2EMD.js';import {eq,and,isNull,gte}from'drizzle-orm';import V from'bcryptjs';import {cookies}from'next/headers';function b(){throw new Error("Function not implemented.")}var O=b;function $(){throw new Error("Function not implemented.")}var N=$;async function H(e,t){await a.delete(f).where(and(eq(f.userID,t),eq(f.type,e)));}var c=H;var F={INVITE:c$2,MFA:d,PASSWORD:d};async function M(e$2,t){let r=e$1(),o=new Date;o.setHours(o.getHours()-F[e$2]);let n=await a.select().from(f).innerJoin(e,and(eq(e.id,f.userID),eq(e.role,r),isNull(e.deletedAt))).where(and(eq(f.id,t),eq(f.type,e$2),gte(f.createdAt,o))).limit(1);return n[0]?{...n[0].resets,user:n[0].user_credentials}:null}var h=M;var q=12;async function C(e){return V.hash(e,q)}var m=C;async function L(e$1,t){let r=await h("PASSWORD",e$1);if(!r)throw new Error("RESET_TOKEN_INVALID");await a.update(e).set({password:await m(t)}).where(eq(e.id,r.userID)),await c("PASSWORD",r.userID);}var X=L;async function Y(e){return f$1("email",e)}var S=Y;var j=48;async function z(e,t){let r=await S(t);if(!r)return null;await c(e,r.id);let o=c$1(null,j);return await a.insert(f).values({createdAt:new Date,id:o,type:e,userID:r.id}),o}var G=z;async function J(e,t){return !!await h(e,t)}var Q=J;function Z(){let e="abcdefghijkmnpqrstuvwxyz23456789",t=new Uint8Array(24);crypto.getRandomValues(t);let r="";for(let o=0;o<t.length;o++)r+=e[t[o]>>3];return r}var R=Z;var te=24,re=3600*1e3;async function oe(e,t=te){g("auth:session","createSession",`Creating session for user ${e} with expiration of ${t} hours`);let r=e$1();g("auth:session","createSession",`Assigned role ${r} to session for user ${e}`);let o=R(),n=R(),g$1=`${o}.${n}`,p=new Date(Date.now()+t*re);await h$1.setItem("session",o,{expires:p,role:r,secret:await m(n),userID:e}),g("auth:session","createSession",`Set session ID ${o} and secret for user ${e} (role ${r}) in storage with expiration at ${p.toISOString()}`),(await cookies()).set(b$1,g$1,{expires:p,httpOnly:true,path:"/",sameSite:"lax",secure:true}),g("auth:session","createSession",`Set cookie '${b$1}' for user ${e} with token ${g$1} and expiration at ${p.toISOString()}`);}var se=oe;async function ae(){let e=await i();e&&(await h$1.removeItem("session",e.id),(await cookies()).delete(b$1));}var ne=ae;function me(){throw new Error("Function not implemented.")}var ue=me;async function fe(e$1){let[t]=await a.insert(e).values({...e$1,password:e$1.password?await m(e$1.password):null}).returning();return t??null}var pe=fe;function le(){throw new Error("Function not implemented.")}var de=le;async function we(e,t){let r=await S(e);if(!r?.password||!await V.compare(t,r.password))throw new a$1({email:"",password:""});return r.id}var he=we;export{O as createMFA,G as createReset,se as createSession,pe as createUser,ne as deleteSession,de as deleteUser,ue as deleteUserSessions,N as updatePasswordWithPassword,X as updatePasswordWithToken,Q as validateReset,he as validateUser};//# sourceMappingURL=index.js.map
1
+ import {a,g,e as e$1,h as h$1,b as b$1,i,d,c as c$2,f as f$1}from'../chunk-4ZSGOMNB.js';export{l as ensureSessionUser,k as getSessionUser,j as validateSession}from'../chunk-4ZSGOMNB.js';import {a as a$1}from'../chunk-AGS5PPG2.js';import'../chunk-37TYQL5Y.js';import {c as c$1}from'../chunk-XSJ4OEIH.js';import {e,f}from'../chunk-JI2U2EMD.js';import {eq,and,isNull,gte}from'drizzle-orm';import V from'bcryptjs';import {cookies}from'next/headers';function b(){throw new Error("Function not implemented.")}var O=b;function $(){throw new Error("Function not implemented.")}var N=$;async function H(e,t){await a.delete(f).where(and(eq(f.userID,t),eq(f.type,e)));}var c=H;var F={INVITE:c$2,MFA:d,PASSWORD:d};async function M(e$2,t){let r=e$1(),o=new Date;o.setHours(o.getHours()-F[e$2]);let n=await a.select().from(f).innerJoin(e,and(eq(e.id,f.userID),eq(e.role,r),isNull(e.deletedAt))).where(and(eq(f.id,t),eq(f.type,e$2),gte(f.createdAt,o))).limit(1);return n[0]?{...n[0].resets,user:n[0].user_credentials}:null}var h=M;var q=12;async function C(e){return V.hash(e,q)}var m=C;async function L(e$1,t){let r=await h("PASSWORD",e$1);if(!r)throw new Error("RESET_TOKEN_INVALID");await a.update(e).set({password:await m(t)}).where(eq(e.id,r.userID)),await c("PASSWORD",r.userID);}var X=L;async function Y(e){return f$1("email",e)}var S=Y;var j=48;async function z(e,t){let r=await S(t);if(!r)return null;await c(e,r.id);let o=c$1(null,j);return await a.insert(f).values({createdAt:new Date,id:o,type:e,userID:r.id}),o}var G=z;async function J(e,t){return !!await h(e,t)}var Q=J;function Z(){let e="abcdefghijkmnpqrstuvwxyz23456789",t=new Uint8Array(24);crypto.getRandomValues(t);let r="";for(let o=0;o<t.length;o++)r+=e[t[o]>>3];return r}var R=Z;var te=24,re=3600*1e3;async function oe(e,t=te){g("auth:session","createSession",`Creating session for user ${e} with expiration of ${t} hours`);let r=e$1();g("auth:session","createSession",`Assigned role ${r} to session for user ${e}`);let o=R(),n=R(),g$1=`${o}.${n}`,p=new Date(Date.now()+t*re);await h$1.setItem("session",o,{expires:p,role:r,secret:await m(n),userID:e}),g("auth:session","createSession",`Set session ID ${o} and secret for user ${e} (role ${r}) in storage with expiration at ${p.toISOString()}`),(await cookies()).set(b$1,g$1,{expires:p,httpOnly:true,path:"/",sameSite:"lax",secure:true}),g("auth:session","createSession",`Set cookie '${b$1}' for user ${e} with token ${g$1} and expiration at ${p.toISOString()}`);}var se=oe;async function ae(){let e=await i();e&&(await h$1.removeItem("session",e.id),(await cookies()).delete(b$1));}var ne=ae;function me(){throw new Error("Function not implemented.")}var ue=me;async function fe(e$1){let[t]=await a.insert(e).values({...e$1,password:e$1.password?await m(e$1.password):null}).returning();return t??null}var pe=fe;function le(){throw new Error("Function not implemented.")}var de=le;async function we(e,t){let r=await S(e);if(!r?.password||!await V.compare(t,r.password))throw new a$1({email:"",password:""});return r.id}var he=we;export{O as createMFA,G as createReset,se as createSession,pe as createUser,ne as deleteSession,de as deleteUser,ue as deleteUserSessions,N as updatePasswordWithPassword,X as updatePasswordWithToken,Q as validateReset,he as validateUser};//# sourceMappingURL=index.js.map
2
2
  //# sourceMappingURL=index.js.map
@@ -0,0 +1,2 @@
1
+ import {e}from'./chunk-JI2U2EMD.js';import N from'bcryptjs';import {cache}from'react';import {createClient}from'redis';import {cookies}from'next/headers';import {and,eq,isNull}from'drizzle-orm';import {drizzle}from'drizzle-orm/node-postgres';function v(e){return process.env.SZ_LOG==="true"?true:typeof process.env.SZ_LOG=="string"?process.env.SZ_LOG.split(",").includes(e):false}function A(e,s,t){v(e)&&console.log(`[${e}] ${s}: ${t}`);}var r=A;var u=null;async function _(){if(!process.env.REDIS_URL)throw new Error("REDIS_URL is not defined. Access to the cache is not possible.");return u||(u=createClient({url:process.env.REDIS_URL}),await u.connect(),u)}var n=_;var w={async getItem(e,s){let t=await(await n()).get(`[${e}]:${s}`);if(!t)return null;try{return JSON.parse(t)}catch{return null}},async getArray(e,s){return await(await n()).sMembers(`[${e}]:${s}`)},async addToArray(e,s,t){await(await n()).sAdd(`[${e}]:${s}`,t);},async removeFromArray(e,s,t){await(await n()).sRem(`[${e}]:${s}`,t);},async setItem(e,s,t){r("[storage]","setItem",`[${e}]:${s} - {${JSON.stringify(t)}}`),await(await n()).set(`[${e}]:${s}`,JSON.stringify(t));},async removeItem(e,s){r("[storage]","removeItem",`[${e}]:${s}`),await(await n()).del(`[${e}]:${s}`);}},c=w;function I(){let e=process.env.AUTH_ROLE;if(!e)throw new Error("AUTH_ROLE environment variable is not set.");let s=parseInt(e,10);if(isNaN(s))throw new Error("AUTH_ROLE environment variable is not a valid number.");return s}var l=I;var m=process.env.AUTH_COOKIE_NAME??"session",z=process.env.AUTH_INVITE_EXPIRY_HOURS?Number(process.env.AUTH_INVITE_EXPIRY_HOURS):24,F=process.env.AUTH_RESET_EXPIRY_HOURS?Number(process.env.AUTH_RESET_EXPIRY_HOURS):2;async function T(e){let s=(e??await cookies()).get(m)?.value;if(!s)return null;let t=s.split(".");if(t.length!==2)return null;let[o,a]=t;return {id:o,secret:a}}var f=T;function $(e){let{expires:s,secret:t,userID:o}=e;if(typeof s!="string"||typeof t!="string"||typeof o!="string")return null;let a=new Date(s);return isNaN(a.getTime())?null:{expires:a,secret:t,userID:o}}var p=$;async function O(e){r("[auth:session]","validateSession","Validating session...");let s=await f(e);if(!s)return r("[auth:session]","validateSession","No session cookie found"),null;r("[auth:session]","validateSession",`Session cookie found with ID: ${s.id}`);let t=l(),o=await c.getItem("session",s.id);return o?.role!==t?(r("[auth:session]","validateSession",`Session role ${o?.role} does not match expected role ${t}`),null):typeof o?.secret!="string"?(r("[auth:session]","validateSession","Session secret is not a string"),null):await N.compare(s.secret,o.secret)?p(o):(r("[auth:session]","validateSession","Session secret does not match"),null)}var P=cache(O),g=P;var d=drizzle(process.env.DATABASE_URL??"");async function k(e$1,s){let t=l();return (await d.select().from(e).where(and(eq(e[e$1],s),eq(e.role,t),isNull(e.deletedAt))).limit(1))[0]??null}var U=k;async function C(e){return U("id",e)}var y=C;async function X(){r("[auth:users]","getSessionUser","Attempting to retrieve session user...");let e=await g();if(!e)return r("[auth:users]","getSessionUser","No valid session found"),null;r("[auth:users]","getSessionUser",`Valid session found for user ID: ${e.userID}`);let s=await y(e.userID);return s?(r("[auth:users]","getSessionUser",`User found for session user ID: ${s.id}`),{email:s.email,id:s.id}):(r("[auth:users]","getSessionUser",`No user found for session user ID: ${e.userID}`),null)}async function Y(){return cache(X)()}var h=Y;async function q(){let e=await h();if(!e)throw new Error("Could not ensure session user. No session user found.");return e}var Ie=q;export{d as a,m as b,z as c,F as d,l as e,U as f,r as g,c as h,f as i,g as j,h as k,Ie as l};//# sourceMappingURL=chunk-4ZSGOMNB.js.map
2
+ //# sourceMappingURL=chunk-4ZSGOMNB.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/utility/log.ts","../src/storage/utility/get-client.ts","../src/storage/index.ts","../src/auth/utility/ensure-role.ts","../src/auth/utility/config.ts","../src/auth/sessions/utility/get-session-cookie.ts","../src/auth/sessions/utility/parse-session.ts","../src/auth/sessions/validate-session.ts","../src/utility/db.ts","../src/auth/users/utility/get-user-by.ts","../src/auth/users/utility/get-user-by-id.ts","../src/auth/users/get-session-user.ts","../src/auth/users/ensure-session-user.ts"],"names":["shouldLog","alias","log","fnName","message","log_default","client","getClient","createClient","get_client_default","serverStorage","prefix","key","value","storage_default","ensureRole","role","roleNumber","ensure_role_default","AUTH_COOKIE_NAME","AUTH_INVITE_EXPIRY_HOURS","AUTH_RESET_EXPIRY_HOURS","getSessionCookie","cookies","cookie","cookieFn","parts","id","secret","get_session_cookie_default","parseSession","session","expires","userID","expiresDate","parse_session_default","uncached_validateSession","bcrypt","validateSession","cache","validate_session_default","db_default","drizzle","getUserBy","authUserTable","and","eq","isNull","get_user_by_default","getUserByID","get_user_by_id_default","uncached_getSessionUser","authUser","getSessionUser","get_session_user_default","ensureSessionUser","user","ensure_session_user_default"],"mappings":"kPAAA,SAASA,CAAAA,CAAUC,CAAAA,CAAwB,CACvC,OAAI,OAAA,CAAQ,GAAA,CAAI,SAAW,MAAA,CAChB,IAAA,CAGP,OAAO,OAAA,CAAQ,GAAA,CAAI,MAAA,EAAW,QAAA,CACX,QAAQ,GAAA,CAAI,MAAA,CAAO,MAAM,GAAG,CAAA,CAC7B,SAASA,CAAK,CAAA,CAG7B,KACX,CAEA,SAASC,CAAAA,CAAID,CAAAA,CAAeE,EAAgBC,CAAAA,CAAuB,CAC3DJ,EAAUC,CAAK,CAAA,EACf,OAAA,CAAQ,GAAA,CAAI,IAAIA,CAAK,C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LOG === 'true') {\n return true;\n }\n\n if (typeof process.env.SZ_LOG === 'string') {\n const logAliases = process.env.SZ_LOG.split(',');\n return logAliases.includes(alias);\n }\n\n return false;\n}\n\nfunction log(alias: string, fnName: string, message: string): void {\n if (shouldLog(alias)) {\n console.log(`[${alias}] ${fnName}: ${message}`); // eslint-disable-line no-console\n }\n}\n\nexport default log;\n","import { createClient } from 'redis';\n\nimport isLocalhost from './is-localhost.js';\n\nlet client: ReturnType<typeof createClient> | null = null;\n\n/**\n * Get a Redis client instance. If the client does not exist, it creates a new one and connects to the Redis server.\n * If the client already exists, it returns the existing instance.\n *\n * @returns A promise that resolves to a Redis client instance.\n */\nasync function getClient(): Promise<ReturnType<typeof createClient>> {\n if (!process.env.REDIS_URL) {\n throw new Error('REDIS_URL is not defined. Access to the cache is not possible.');\n }\n\n if (client) {\n return client;\n }\n\n client = createClient({\n url: process.env.REDIS_URL,\n });\n\n await client.connect();\n return client;\n}\n\nexport default getClient;\n","import log from '../utility/log';\n\nimport getClient from './utility/get-client';\n\n/**\n * Server-side storage utility for caching data using Redis. It is designed to match the interface of localStorage, but operates on the server side.\n */\nconst serverStorage = {\n /**\n * Get an item from the cache.\n * @param prefix The prefix to use for the cache key.\n * @param key The key of the item to retrieve.\n * @returns The cached item, or null if not found.\n */\n async getItem(prefix: string, key: string): Promise<Record<string, unknown> | null> {\n const value = await (await getClient()).get(`[${prefix}]:${key}`);\n\n if (!value) {\n return null;\n }\n\n try {\n return JSON.parse(value);\n } catch {\n return null;\n }\n },\n\n async getArray(prefix: string, key: string): Promise<string[]> {\n const values = await (await getClient()).sMembers(`[${prefix}]:${key}`);\n return values;\n },\n\n async addToArray(prefix: string, key: string, value: string): Promise<void> {\n await (await getClient()).sAdd(`[${prefix}]:${key}`, value);\n },\n\n async removeFromArray(prefix: string, key: string, value: string): Promise<void> {\n await (await getClient()).sRem(`[${prefix}]:${key}`, value);\n },\n\n /**\n * Set an item in the cache.\n * @param prefix The prefix to use for the cache key.\n * @param key The key of the item to set.\n * @param value The value of the item to set.\n */\n async setItem(prefix: string, key: string, value: Record<string, unknown>): Promise<void> {\n log('[storage]', 'setItem', `[${prefix}]:${key} - {${JSON.stringify(value)}}`);\n await (await getClient()).set(`[${prefix}]:${key}`, JSON.stringify(value));\n },\n\n /**\n * Remove an item from the cache.\n * @param prefix The prefix to use for the cache key.\n * @param key The key of the item to remove.\n */\n async removeItem(prefix: string, key: string): Promise<void> {\n log('[storage]', 'removeItem', `[${prefix}]:${key}`);\n await (await getClient()).del(`[${prefix}]:${key}`);\n },\n};\n\nexport default serverStorage;\n","function ensureRole(): number {\n const role = process.env.AUTH_ROLE;\n\n if (!role) {\n throw new Error('AUTH_ROLE environment variable is not set.');\n }\n\n const roleNumber = parseInt(role, 10);\n\n if (isNaN(roleNumber)) {\n throw new Error('AUTH_ROLE environment variable is not a valid number.');\n }\n\n return roleNumber;\n}\n\nexport default ensureRole;\n","export const AUTH_COOKIE_NAME = process.env.AUTH_COOKIE_NAME ?? 'session';\n\nexport const AUTH_INVITE_EXPIRY_HOURS = process.env.AUTH_INVITE_EXPIRY_HOURS\n ? Number(process.env.AUTH_INVITE_EXPIRY_HOURS)\n : 24;\n\nexport const AUTH_RESET_EXPIRY_HOURS = process.env.AUTH_RESET_EXPIRY_HOURS\n ? Number(process.env.AUTH_RESET_EXPIRY_HOURS)\n : 2;\n","import { cookies as cookieFn } from 'next/headers';\nimport { NextRequest } from 'next/server';\n\nimport { AUTH_COOKIE_NAME } from '../../utility/config';\n\nimport type { AuthSessionCookie } from './interfaces';\n\nasync function getSessionCookie(\n cookies?: NextRequest['cookies']\n): Promise<AuthSessionCookie | null> {\n const cookie = (cookies ?? (await cookieFn())).get(AUTH_COOKIE_NAME)?.value;\n\n if (!cookie) {\n return null;\n }\n\n const parts = cookie.split('.');\n\n if (parts.length !== 2) {\n return null;\n }\n\n const [id, secret] = parts;\n return { id, secret };\n}\n\nexport default getSessionCookie;\n","import type { AuthSession } from './interfaces';\n\nfunction parseSession(session: Record<string, unknown>): AuthSession | null {\n const { expires, secret, userID } = session;\n\n if (typeof expires !== 'string' || typeof secret !== 'string' || typeof userID !== 'string') {\n return null;\n }\n\n const expiresDate = new Date(expires);\n\n if (isNaN(expiresDate.getTime())) {\n return null;\n }\n\n return {\n expires: expiresDate,\n secret,\n userID,\n };\n}\n\nexport default parseSession;\n","import bcrypt from 'bcryptjs';\nimport { NextRequest } from 'next/server';\nimport { cache } from 'react';\n\nimport serverStorage from '../../storage';\nimport log from '../../utility/log';\n\nimport ensureRole from '../utility/ensure-role';\nimport getSessionCookie from './utility/get-session-cookie';\nimport type { AuthSession } from './utility/interfaces';\nimport parseSession from './utility/parse-session';\n\nasync function uncached_validateSession(\n cookies?: NextRequest['cookies']\n): Promise<AuthSession | null> {\n log('[auth:session]', 'validateSession', 'Validating session...');\n\n const cookie = await getSessionCookie(cookies);\n\n if (!cookie) {\n log('[auth:session]', 'validateSession', 'No session cookie found');\n return null;\n }\n\n log('[auth:session]', 'validateSession', `Session cookie found with ID: ${cookie.id}`);\n\n const role = ensureRole();\n const session = await serverStorage.getItem('session', cookie.id);\n\n if (session?.role !== role) {\n log(\n '[auth:session]',\n 'validateSession',\n `Session role ${session?.role} does not match expected role ${role}`\n );\n return null;\n }\n\n if (typeof session?.secret !== 'string') {\n log('[auth:session]', 'validateSession', 'Session secret is not a string');\n return null;\n }\n\n if (!(await bcrypt.compare(cookie.secret, session.secret))) {\n log('[auth:session]', 'validateSession', 'Session secret does not match');\n return null;\n }\n\n return parseSession(session);\n}\n\nconst validateSession = cache(uncached_validateSession);\n\nexport default validateSession;\n","import { drizzle } from 'drizzle-orm/node-postgres';\n\nexport default drizzle(process.env.DATABASE_URL ?? '');\n","import { and, eq, isNull } from 'drizzle-orm';\n\nimport db from '../../../utility/db';\n\nimport ensureRole from '../../utility/ensure-role';\nimport { authUserTable } from '../../utility/schema';\nimport type { AuthUserTable } from '../../utility/schema';\n\nimport type { AuthUser } from './interfaces';\n\nasync function getUserBy(key: keyof AuthUserTable, value: string): Promise<AuthUser | null> {\n const role = ensureRole();\n\n const results = await db\n .select()\n .from(authUserTable)\n .where(\n and(\n eq(authUserTable[key], value),\n eq(authUserTable.role, role),\n isNull(authUserTable.deletedAt)\n )\n )\n .limit(1);\n\n return results[0] ?? null;\n}\n\nexport default getUserBy;\n","import getUserBy from './get-user-by';\nimport type { AuthUser } from './interfaces';\n\nasync function getUserByID(id: string): Promise<AuthUser | null> {\n return getUserBy('id', id);\n}\n\nexport default getUserByID;\n","import { cache } from 'react';\n\nimport log from '../../utility/log';\n\nimport validateSession from '../sessions/validate-session';\n\nimport getUserByID from './utility/get-user-by-id';\nimport type { User } from './utility/interfaces';\n\nasync function uncached_getSessionUser(): Promise<User | null> {\n log('[auth:users]', 'getSessionUser', 'Attempting to retrieve session user...');\n\n const session = await validateSession();\n\n if (!session) {\n log('[auth:users]', 'getSessionUser', 'No valid session found');\n return null;\n }\n\n log('[auth:users]', 'getSessionUser', `Valid session found for user ID: ${session.userID}`);\n\n const authUser = await getUserByID(session.userID);\n\n if (!authUser) {\n log(\n '[auth:users]',\n 'getSessionUser',\n `No user found for session user ID: ${session.userID}`\n );\n return null;\n }\n\n log('[auth:users]', 'getSessionUser', `User found for session user ID: ${authUser.id}`);\n\n return {\n email: authUser.email,\n id: authUser.id,\n };\n}\n\nasync function getSessionUser(): ReturnType<typeof uncached_getSessionUser> {\n return cache(uncached_getSessionUser)();\n}\n\nexport default getSessionUser;\n","import getSessionUser from './get-session-user';\nimport type { User } from './utility/interfaces';\n\nasync function ensureSessionUser(): Promise<User> {\n const user = await getSessionUser();\n\n if (!user) {\n throw new Error('Could not ensure session user. No session user found.');\n }\n\n return user;\n}\n\nexport default ensureSessionUser;\n"]}
@@ -1,2 +1,2 @@
1
- import {l}from'../chunk-UQQMJZWP.js';import {d,b,c}from'../chunk-XSJ4OEIH.js';import'../chunk-JI2U2EMD.js';import {cache}from'react';import {pick}from'@sqrzro/utility';import {eq}from'drizzle-orm';import {notFound}from'next/navigation';function k(e){async function y(t){if(!e.makeQuery)throw new Error("Could not `getAll`. `makeQuery` function is not defined.");let r=[],a=await e.applyFilters?.(t?.filters??null);r.push(...a||[]);let n=await e.applyGuards?.(t?.guards??null);return r.push(...n||[]),e.makeQuery(r,{limit:t?.limit??-1,offset:t?.offset??0})}async function f(t){if(!e.makeMetaQuery)throw new Error("Could not `getPaginated`. `makeMetaQuery` function is not defined.");if(!e.makeQuery)throw new Error("Could not `getPaginated`. `makeQuery` function is not defined.");let r=[],a=await e.applyFilters?.(t?.filters??null);r.push(...a||[]);let n=await e.applyGuards?.(t?.guards??null);r.push(...n||[]);let s=await e.makeMetaQuery(r);return {data:await e.makeQuery(r,{limit:t?.limit??10,offset:((t?.page??1)-1)*(t?.limit??10)}),meta:{limit:t?.limit??10,page:t?.page??1,total:s.count}}}async function o(t,r){if(!e.idColumn)throw new Error("Could not `getByID`. `idColumn` is not defined.");if(!e.makeQuery)throw new Error("Could not `getByID`. `makeQuery` function is not defined.");let a=[],n=await e.applyGuards?.(r?.guards??null);a.push(...n||[]);let s=await e.applyFilters?.(r?.filters??null);a.push(...s||[]),a.push(eq(e.idColumn,t));let[u]=await e.makeQuery(a,{limit:1,offset:0});return u||null}async function p(t){if(!e.paramKey)throw new Error("Could not `getFromParams`. `paramKey` is not defined.");if(!e.prefix)throw new Error("Could not `getFromParams`. `prefix` is not defined.");let r=await d(e.paramKey,e.prefix,t),a=await o(r);return a||notFound()}async function w(){if(!e.prefix)throw new Error("Could not `getFromSession`. `prefix` is not defined.");let t=await l(),r=b(t.id,e.prefix),a=await o(r);if(!a)throw new Error(`Could not \`getFromSession\`. No record with ID '${r}' found.`);return a}async function h(t){if(!e.makeCreateMutation)throw new Error("Could not `create`. `makeCreateMutation` is not defined.");let r={id:c(e.prefix),...pick(t,e.fillable||[])};return e.makeCreateMutation(r)}async function P(t){if(!e.makeUpdateMutation)throw new Error("Could not `update`. `makeUpdateMutation` is not defined.");return e.makeUpdateMutation(t)}return {create:h,getAll:(...t)=>cache(y)(...t),getByID:(...t)=>cache(o)(...t),getFromParams:(...t)=>cache(p)(...t),getFromSession:(...t)=>cache(w)(...t),getPaginated:(...t)=>cache(f)(...t),update:P}}var I=k;export{I as createRepository};//# sourceMappingURL=index.js.map
1
+ import {l}from'../chunk-4ZSGOMNB.js';import {d,b,c}from'../chunk-XSJ4OEIH.js';import'../chunk-JI2U2EMD.js';import {cache}from'react';import {pick}from'@sqrzro/utility';import {eq}from'drizzle-orm';import {notFound}from'next/navigation';function k(e){async function y(t){if(!e.makeQuery)throw new Error("Could not `getAll`. `makeQuery` function is not defined.");let r=[],a=await e.applyFilters?.(t?.filters??null);r.push(...a||[]);let n=await e.applyGuards?.(t?.guards??null);return r.push(...n||[]),e.makeQuery(r,{limit:t?.limit??-1,offset:t?.offset??0})}async function f(t){if(!e.makeMetaQuery)throw new Error("Could not `getPaginated`. `makeMetaQuery` function is not defined.");if(!e.makeQuery)throw new Error("Could not `getPaginated`. `makeQuery` function is not defined.");let r=[],a=await e.applyFilters?.(t?.filters??null);r.push(...a||[]);let n=await e.applyGuards?.(t?.guards??null);r.push(...n||[]);let s=await e.makeMetaQuery(r);return {data:await e.makeQuery(r,{limit:t?.limit??10,offset:((t?.page??1)-1)*(t?.limit??10)}),meta:{limit:t?.limit??10,page:t?.page??1,total:s.count}}}async function o(t,r){if(!e.idColumn)throw new Error("Could not `getByID`. `idColumn` is not defined.");if(!e.makeQuery)throw new Error("Could not `getByID`. `makeQuery` function is not defined.");let a=[],n=await e.applyGuards?.(r?.guards??null);a.push(...n||[]);let s=await e.applyFilters?.(r?.filters??null);a.push(...s||[]),a.push(eq(e.idColumn,t));let[u]=await e.makeQuery(a,{limit:1,offset:0});return u||null}async function p(t){if(!e.paramKey)throw new Error("Could not `getFromParams`. `paramKey` is not defined.");if(!e.prefix)throw new Error("Could not `getFromParams`. `prefix` is not defined.");let r=await d(e.paramKey,e.prefix,t),a=await o(r);return a||notFound()}async function w(){if(!e.prefix)throw new Error("Could not `getFromSession`. `prefix` is not defined.");let t=await l(),r=b(t.id,e.prefix),a=await o(r);if(!a)throw new Error(`Could not \`getFromSession\`. No record with ID '${r}' found.`);return a}async function h(t){if(!e.makeCreateMutation)throw new Error("Could not `create`. `makeCreateMutation` is not defined.");let r={id:c(e.prefix),...pick(t,e.fillable||[])};return e.makeCreateMutation(r)}async function P(t){if(!e.makeUpdateMutation)throw new Error("Could not `update`. `makeUpdateMutation` is not defined.");return e.makeUpdateMutation(t)}return {create:h,getAll:(...t)=>cache(y)(...t),getByID:(...t)=>cache(o)(...t),getFromParams:(...t)=>cache(p)(...t),getFromSession:(...t)=>cache(w)(...t),getPaginated:(...t)=>cache(f)(...t),update:P}}var I=k;export{I as createRepository};//# sourceMappingURL=index.js.map
2
2
  //# sourceMappingURL=index.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sqrzro/server",
3
- "version": "4.0.0-alpha.10",
3
+ "version": "4.0.0-alpha.11",
4
4
  "type": "module",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -1,2 +0,0 @@
1
- import {e}from'./chunk-JI2U2EMD.js';import O from'bcryptjs';import {cache}from'react';import {createClient}from'redis';import {cookies}from'next/headers';import {and,eq,isNull}from'drizzle-orm';import {drizzle}from'drizzle-orm/node-postgres';function A(e){return process.env.SZ_LOG==="true"?true:typeof process.env.SZ_LOG=="string"?process.env.SZ_LOG.split(",").includes(e):false}function _(e,t,r){A(e)&&console.log(`[${e}] ${t}: ${r}`);}var l=_;var i=null;async function v(){if(!process.env.REDIS_URL)throw new Error("REDIS_URL is not defined. Access to the cache is not possible.");return i||(i=createClient({url:process.env.REDIS_URL}),await i.connect(),i)}var o=v;var E={async getItem(e,t){let r=await(await o()).get(`[${e}]:${t}`);if(!r)return null;try{return JSON.parse(r)}catch{return null}},async getArray(e,t){return await(await o()).sMembers(`[${e}]:${t}`)},async addToArray(e,t,r){await(await o()).sAdd(`[${e}]:${t}`,r);},async removeFromArray(e,t,r){await(await o()).sRem(`[${e}]:${t}`,r);},async setItem(e,t,r){l("[storage]","setItem",`[${e}]:${t} - {${JSON.stringify(r)}}`),await(await o()).set(`[${e}]:${t}`,JSON.stringify(r));},async removeItem(e,t){l("[storage]","removeItem",`[${e}]:${t}`),await(await o()).del(`[${e}]:${t}`);}},c=E;function h(){let e=process.env.AUTH_ROLE;if(!e)throw new Error("AUTH_ROLE environment variable is not set.");let t=parseInt(e,10);if(isNaN(t))throw new Error("AUTH_ROLE environment variable is not a valid number.");return t}var a=h;var m=process.env.AUTH_COOKIE_NAME??"session",z=process.env.AUTH_INVITE_EXPIRY_HOURS?Number(process.env.AUTH_INVITE_EXPIRY_HOURS):24,F=process.env.AUTH_RESET_EXPIRY_HOURS?Number(process.env.AUTH_RESET_EXPIRY_HOURS):2;async function T(e){let t=(e??await cookies()).get(m)?.value;if(!t)return null;let r=t.split(".");if(r.length!==2)return null;let[s,u]=r;return {id:s,secret:u}}var f=T;function N(e){let{expires:t,secret:r,userID:s}=e;if(typeof t!="string"||typeof r!="string"||typeof s!="string")return null;let u=new Date(t);return isNaN(u.getTime())?null:{expires:u,secret:r,userID:s}}var p=N;async function $(e){let t=await f(e);if(!t)return null;let r=a(),s=await c.getItem("session",t.id);return s?.role!==r||typeof s?.secret!="string"||!await O.compare(t.secret,s.secret)?null:p(s)}var P=cache($),g=P;var d=drizzle(process.env.DATABASE_URL??"");async function k(e$1,t){let r=a();return (await d.select().from(e).where(and(eq(e[e$1],t),eq(e.role,r),isNull(e.deletedAt))).limit(1))[0]??null}var U=k;async function L(e){return U("id",e)}var R=L;async function X(){let e=await g();if(!e)return null;let t=await R(e.userID);return t?{email:t.email,id:t.id}:null}async function Y(){return cache(X)()}var S=Y;async function q(){let e=await S();if(!e)throw new Error("Could not ensure session user. No session user found.");return e}var ve=q;export{d as a,m as b,z as c,F as d,a as e,U as f,l as g,c as h,f as i,g as j,S as k,ve as l};//# sourceMappingURL=chunk-UQQMJZWP.js.map
2
- //# sourceMappingURL=chunk-UQQMJZWP.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/utility/log.ts","../src/storage/utility/get-client.ts","../src/storage/index.ts","../src/auth/utility/ensure-role.ts","../src/auth/utility/config.ts","../src/auth/sessions/utility/get-session-cookie.ts","../src/auth/sessions/utility/parse-session.ts","../src/auth/sessions/validate-session.ts","../src/utility/db.ts","../src/auth/users/utility/get-user-by.ts","../src/auth/users/utility/get-user-by-id.ts","../src/auth/users/get-session-user.ts","../src/auth/users/ensure-session-user.ts"],"names":["shouldLog","alias","log","fnName","message","log_default","client","getClient","createClient","get_client_default","serverStorage","prefix","key","value","storage_default","ensureRole","role","roleNumber","ensure_role_default","AUTH_COOKIE_NAME","AUTH_INVITE_EXPIRY_HOURS","AUTH_RESET_EXPIRY_HOURS","getSessionCookie","cookies","cookie","cookieFn","parts","id","secret","get_session_cookie_default","parseSession","session","expires","userID","expiresDate","parse_session_default","uncached_validateSession","bcrypt","validateSession","cache","validate_session_default","db_default","drizzle","getUserBy","authUserTable","and","eq","isNull","get_user_by_default","getUserByID","get_user_by_id_default","uncached_getSessionUser","authUser","getSessionUser","get_session_user_default","ensureSessionUser","user","ensure_session_user_default"],"mappings":"kPAAA,SAASA,CAAAA,CAAUC,CAAAA,CAAwB,CACvC,OAAI,OAAA,CAAQ,GAAA,CAAI,MAAA,GAAW,OAChB,IAAA,CAGP,OAAO,OAAA,CAAQ,GAAA,CAAI,QAAW,QAAA,CACX,OAAA,CAAQ,GAAA,CAAI,MAAA,CAAO,MAAM,GAAG,CAAA,CAC7B,QAAA,CAASA,CAAK,EAG7B,KACX,CAEA,SAASC,CAAAA,CAAID,EAAeE,CAAAA,CAAgBC,CAAAA,CAAuB,CAC3DJ,CAAAA,CAAUC,CAAK,CAAA,EACf,OAAA,CAAQ,GAAA,CAAI,IAAIA,CAAK,CAAA,EAAA,EAAKE,CAAM,CAAA,EAAA,EAAKC,CAAO,CAAA,CAAE,EAEtD,CAEA,I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,CAAAA,CAAQ,MAAM,CAAA,CAEjD,OAAKqB,CAAAA,CAIE,CACH,MAAOA,CAAAA,CAAS,KAAA,CAChB,EAAA,CAAIA,CAAAA,CAAS,EACjB,CAAA,CANW,IAOf,CAEA,eAAeC,GAA6D,CACxE,OAAOd,KAAAA,CAAMY,CAAuB,GACxC,CAEA,IAAOG,CAAAA,CAAQD,EC3Bf,eAAeE,CAAAA,EAAmC,CAC9C,IAAMC,EAAO,MAAMF,CAAAA,EAAe,CAElC,GAAI,CAACE,CAAAA,CACD,MAAM,IAAI,KAAA,CAAM,uDAAuD,CAAA,CAG3E,OAAOA,CACX,KAEOC,EAAAA,CAAQF","file":"chunk-UQQMJZWP.js","sourcesContent":["function shouldLog(alias: string): boolean {\n if (process.env.SZ_LOG === 'true') {\n return true;\n }\n\n if (typeof process.env.SZ_LOG === 'string') {\n const logAliases = process.env.SZ_LOG.split(',');\n return logAliases.includes(alias);\n }\n\n return false;\n}\n\nfunction log(alias: string, fnName: string, message: string): void {\n if (shouldLog(alias)) {\n console.log(`[${alias}] ${fnName}: ${message}`); // eslint-disable-line no-console\n }\n}\n\nexport default log;\n","import { createClient } from 'redis';\n\nimport isLocalhost from './is-localhost.js';\n\nlet client: ReturnType<typeof createClient> | null = null;\n\n/**\n * Get a Redis client instance. If the client does not exist, it creates a new one and connects to the Redis server.\n * If the client already exists, it returns the existing instance.\n *\n * @returns A promise that resolves to a Redis client instance.\n */\nasync function getClient(): Promise<ReturnType<typeof createClient>> {\n if (!process.env.REDIS_URL) {\n throw new Error('REDIS_URL is not defined. Access to the cache is not possible.');\n }\n\n if (client) {\n return client;\n }\n\n client = createClient({\n url: process.env.REDIS_URL,\n });\n\n await client.connect();\n return client;\n}\n\nexport default getClient;\n","import log from '../utility/log';\n\nimport getClient from './utility/get-client';\n\n/**\n * Server-side storage utility for caching data using Redis. It is designed to match the interface of localStorage, but operates on the server side.\n */\nconst serverStorage = {\n /**\n * Get an item from the cache.\n * @param prefix The prefix to use for the cache key.\n * @param key The key of the item to retrieve.\n * @returns The cached item, or null if not found.\n */\n async getItem(prefix: string, key: string): Promise<Record<string, unknown> | null> {\n const value = await (await getClient()).get(`[${prefix}]:${key}`);\n\n if (!value) {\n return null;\n }\n\n try {\n return JSON.parse(value);\n } catch {\n return null;\n }\n },\n\n async getArray(prefix: string, key: string): Promise<string[]> {\n const values = await (await getClient()).sMembers(`[${prefix}]:${key}`);\n return values;\n },\n\n async addToArray(prefix: string, key: string, value: string): Promise<void> {\n await (await getClient()).sAdd(`[${prefix}]:${key}`, value);\n },\n\n async removeFromArray(prefix: string, key: string, value: string): Promise<void> {\n await (await getClient()).sRem(`[${prefix}]:${key}`, value);\n },\n\n /**\n * Set an item in the cache.\n * @param prefix The prefix to use for the cache key.\n * @param key The key of the item to set.\n * @param value The value of the item to set.\n */\n async setItem(prefix: string, key: string, value: Record<string, unknown>): Promise<void> {\n log('[storage]', 'setItem', `[${prefix}]:${key} - {${JSON.stringify(value)}}`);\n await (await getClient()).set(`[${prefix}]:${key}`, JSON.stringify(value));\n },\n\n /**\n * Remove an item from the cache.\n * @param prefix The prefix to use for the cache key.\n * @param key The key of the item to remove.\n */\n async removeItem(prefix: string, key: string): Promise<void> {\n log('[storage]', 'removeItem', `[${prefix}]:${key}`);\n await (await getClient()).del(`[${prefix}]:${key}`);\n },\n};\n\nexport default serverStorage;\n","function ensureRole(): number {\n const role = process.env.AUTH_ROLE;\n\n if (!role) {\n throw new Error('AUTH_ROLE environment variable is not set.');\n }\n\n const roleNumber = parseInt(role, 10);\n\n if (isNaN(roleNumber)) {\n throw new Error('AUTH_ROLE environment variable is not a valid number.');\n }\n\n return roleNumber;\n}\n\nexport default ensureRole;\n","export const AUTH_COOKIE_NAME = process.env.AUTH_COOKIE_NAME ?? 'session';\n\nexport const AUTH_INVITE_EXPIRY_HOURS = process.env.AUTH_INVITE_EXPIRY_HOURS\n ? Number(process.env.AUTH_INVITE_EXPIRY_HOURS)\n : 24;\n\nexport const AUTH_RESET_EXPIRY_HOURS = process.env.AUTH_RESET_EXPIRY_HOURS\n ? Number(process.env.AUTH_RESET_EXPIRY_HOURS)\n : 2;\n","import { cookies as cookieFn } from 'next/headers';\nimport { NextRequest } from 'next/server';\n\nimport { AUTH_COOKIE_NAME } from '../../utility/config';\n\nimport type { AuthSessionCookie } from './interfaces';\n\nasync function getSessionCookie(\n cookies?: NextRequest['cookies']\n): Promise<AuthSessionCookie | null> {\n const cookie = (cookies ?? (await cookieFn())).get(AUTH_COOKIE_NAME)?.value;\n\n if (!cookie) {\n return null;\n }\n\n const parts = cookie.split('.');\n\n if (parts.length !== 2) {\n return null;\n }\n\n const [id, secret] = parts;\n return { id, secret };\n}\n\nexport default getSessionCookie;\n","import type { AuthSession } from './interfaces';\n\nfunction parseSession(session: Record<string, unknown>): AuthSession | null {\n const { expires, secret, userID } = session;\n\n if (typeof expires !== 'string' || typeof secret !== 'string' || typeof userID !== 'string') {\n return null;\n }\n\n const expiresDate = new Date(expires);\n\n if (isNaN(expiresDate.getTime())) {\n return null;\n }\n\n return {\n expires: expiresDate,\n secret,\n userID,\n };\n}\n\nexport default parseSession;\n","import bcrypt from 'bcryptjs';\nimport { NextRequest } from 'next/server';\nimport { cache } from 'react';\n\nimport serverStorage from '../../storage';\n\nimport ensureRole from '../utility/ensure-role';\nimport getSessionCookie from './utility/get-session-cookie';\nimport type { AuthSession } from './utility/interfaces';\nimport parseSession from './utility/parse-session';\n\nasync function uncached_validateSession(\n cookies?: NextRequest['cookies']\n): Promise<AuthSession | null> {\n const cookie = await getSessionCookie(cookies);\n\n if (!cookie) {\n return null;\n }\n\n const role = ensureRole();\n const session = await serverStorage.getItem('session', cookie.id);\n\n if(session?.role !== role) {\n return null;\n }\n\n if (typeof session?.secret !== 'string') {\n return null;\n }\n\n if (!(await bcrypt.compare(cookie.secret, session.secret))) {\n return null;\n }\n\n return parseSession(session);\n}\n\nconst validateSession = cache(uncached_validateSession);\n\nexport default validateSession;\n","import { drizzle } from 'drizzle-orm/node-postgres';\n\nexport default drizzle(process.env.DATABASE_URL ?? '');\n","import { and, eq, isNull } from 'drizzle-orm';\n\nimport db from '../../../utility/db';\n\nimport ensureRole from '../../utility/ensure-role';\nimport { authUserTable } from '../../utility/schema';\nimport type { AuthUserTable } from '../../utility/schema';\n\nimport type { AuthUser } from './interfaces';\n\nasync function getUserBy(key: keyof AuthUserTable, value: string): Promise<AuthUser | null> {\n const role = ensureRole();\n\n const results = await db\n .select()\n .from(authUserTable)\n .where(\n and(\n eq(authUserTable[key], value),\n eq(authUserTable.role, role),\n isNull(authUserTable.deletedAt)\n )\n )\n .limit(1);\n\n return results[0] ?? null;\n}\n\nexport default getUserBy;\n","import getUserBy from './get-user-by';\nimport type { AuthUser } from './interfaces';\n\nasync function getUserByID(id: string): Promise<AuthUser | null> {\n return getUserBy('id', id);\n}\n\nexport default getUserByID;\n","import { cache } from 'react';\n\nimport validateSession from '../sessions/validate-session';\n\nimport getUserByID from './utility/get-user-by-id';\nimport type { User } from './utility/interfaces';\n\nasync function uncached_getSessionUser(): Promise<User | null> {\n const session = await validateSession();\n\n if (!session) {\n return null;\n }\n\n const authUser = await getUserByID(session.userID);\n\n if (!authUser) {\n return null;\n }\n\n return {\n email: authUser.email,\n id: authUser.id,\n };\n}\n\nasync function getSessionUser(): ReturnType<typeof uncached_getSessionUser> {\n return cache(uncached_getSessionUser)();\n}\n\nexport default getSessionUser;\n","import getSessionUser from './get-session-user';\nimport type { User } from './utility/interfaces';\n\nasync function ensureSessionUser(): Promise<User> {\n const user = await getSessionUser();\n\n if (!user) {\n throw new Error('Could not ensure session user. No session user found.');\n }\n\n return user;\n}\n\nexport default ensureSessionUser;\n"]}