@kyro-cms/core 0.12.18 → 0.12.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api-handler-graphql.cjs +1 -1
- package/dist/api-handler-graphql.js +1 -1
- package/dist/api-handler-trpc.cjs +1 -1
- package/dist/api-handler-trpc.js +1 -1
- package/dist/api-handler.cjs +1 -1
- package/dist/api-handler.js +1 -1
- package/dist/bootstrap-4WXRKXMO.cjs +1 -0
- package/dist/{bootstrap-A3OBR3YI.js → bootstrap-KFGRTJSD.js} +1 -1
- package/dist/{chunk-CPGTIDGM.js → chunk-3NC7GXD5.js} +3 -3
- package/dist/{chunk-7USZ4YRI.js → chunk-4D6FG2J6.js} +1 -1
- package/dist/chunk-5K4YG5DA.cjs +300 -0
- package/dist/chunk-6J27P5D6.js +300 -0
- package/dist/{chunk-QMQXKCCQ.cjs → chunk-KJT6VTTN.cjs} +1 -1
- package/dist/chunk-O3OYZQN7.cjs +21 -0
- package/dist/chunk-OOQGI3T7.js +1 -0
- package/dist/chunk-QJZQOLRN.js +21 -0
- package/dist/{chunk-RNCVLIKD.cjs → chunk-SFAD6WPC.cjs} +3 -3
- package/dist/{chunk-JAJ6ZWAQ.cjs → chunk-XALG5H27.cjs} +1 -1
- package/dist/chunk-XTRY75KC.cjs +210 -0
- package/dist/chunk-YVM5BDRD.js +210 -0
- package/dist/cli/index.cjs +1 -1
- package/dist/cli/index.js +1 -1
- package/dist/index.cjs +3 -3
- package/dist/index.d.cts +105 -1
- package/dist/index.d.ts +105 -1
- package/dist/index.js +1 -1
- package/dist/rest/index.cjs +1 -1
- package/dist/rest/index.js +1 -1
- package/dist/templates/index.cjs +1 -1
- package/dist/templates/index.js +1 -1
- package/package.json +1 -1
- package/dist/bootstrap-YLGVKTQS.cjs +0 -1
- package/dist/chunk-6NGUY76Y.js +0 -259
- package/dist/chunk-EQIAXBR4.cjs +0 -86
- package/dist/chunk-GCQTSPX6.cjs +0 -259
- package/dist/chunk-HRNAHWDS.js +0 -21
- package/dist/chunk-O62KJ2J7.js +0 -1
- package/dist/chunk-ODPUHZUA.js +0 -86
- package/dist/chunk-RDKCMKBE.cjs +0 -21
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export{a as RedisAuthAdapter}from'./chunk-QOCHBPMK.js';export{R as allSettingsGlobals,c as blogCollections,d as blogGlobals,S as coreSettingsGlobals,W as createTemplateConfig,e as ecommerceCollections,f as ecommerceGlobals,g as kitchenSinkCollections,i as mediaCollections,a as minimalCollections,V as templateCollections}from'./chunk-CPGTIDGM.js';export{a as kyro}from'./chunk-PTS33SK5.js';export{s as AnalyticsPlugin,t as CommentsPlugin,a as ConfigValidationError,y as Kyro,p as KyroPlugin,A as LocalAdapter,q as PluginManager,l as Registry,u as ReviewsPlugin,r as SEOPlugin,v as WishlistPlugin,x as applyCollectionOverrides,h as collectionToCreateZod,i as collectionToUpdateZod,j as collectionToWhereZod,g as collectionToZod,z as createKyro,B as createLocalAdapter,o as createRegistry,f as fieldToZod,m as getRegistry,k as globalToZod,w as presetPlugins,n as resetRegistry,b as validateCollection,e as validateConfig,d as validateFields,c as validateGlobal}from'./chunk-HRNAHWDS.js';export{d as autoBootstrap,a as bootstrapAdmin,e as bootstrapWithRetry,c as getBootstrapFromEnv}from'./chunk-O62KJ2J7.js';import'./chunk-NZ35PV5R.js';export{a as CSSGenerator,g as createAdminStyling,d as defaultDarkTheme,h as defaultFieldStyling,c as defaultLightTheme,e as ecommerce2026Theme,f as generateCSSVariables,b as generateTailwindConfig}from'./chunk-UHFDH3PG.js';export{q as ALL_FIELD_TYPES,n as COMPLEX_FIELD_TYPES,p as LAYOUT_FIELD_TYPES,m as PRIMITIVE_FIELD_TYPES,o as RELATIONAL_FIELD_TYPES,d as isArrayField,f as isBlocksField,e as isGroupField,h as isImageField,k as isLayoutField,b as isNumberField,c as isRelationshipField,i as isRichTextField,j as isSelectField,a as isTextField,g as isUploadField,t as normalizeRichTextValue,u as renderRichText,s as richTextStyles}from'./chunk-INB4LNA6.js';import'./chunk-5SEHX7ON.js';export{a as createContext,g as createCountProcedure,d as createCreateProcedure,f as createDeleteProcedure,h as createDynamicRouter,c as createFindByIDProcedure,b as createFindProcedure,i as createKyroServer,e as createUpdateProcedure}from'./chunk-LHW4R367.js';export{c as buildGraphQLSchema,d as createGraphQLSchema}from'./chunk-PP7W5UKL.js';import {l,n,m,p,q as q$1}from'./chunk-ODPUHZUA.js';export{n as AuditLogger,p as InMemoryAuditLogger,m as InMemoryRateLimiter,s as MediaService,o as createAuditContext,t as createHonoApp,e as createLocalStorage,u as createRESTAPI,i as getAppSecret,j as getEncryptionKey,k as getSessionConfig,r as isEdgeRuntime,h as loadSecrets,d as resolveProvider,g as setDbAdapter}from'./chunk-ODPUHZUA.js';import {b,c}from'./chunk-6NGUY76Y.js';export{a as ConfigService,b as EmailTransport,c as PasswordPolicy}from'./chunk-6NGUY76Y.js';import'./chunk-K6WUOU6P.js';import'./chunk-IETGL7WJ.js';import {a as a$2}from'./chunk-IKOXCJYO.js';export{a as SQLiteAuthAdapter}from'./chunk-IKOXCJYO.js';import'./chunk-NRLIGDYF.js';export{e as ALL_WEBHOOK_EVENTS,f as WEBHOOK_COLLECTION,g as WEBHOOK_DELIVERY_COLLECTION,d as WEBHOOK_EVENTS,n as WebhookService,l as buildDeliveryRecord,m as createTestPayload,o as createWebhookService,j as deliverWebhook,k as deliverWithRetry,i as generateWebhookSecret,h as signPayload}from'./chunk-FVZ5RFLO.js';export{a as evaluateAccess,c as getWhereClause,b as mergeWhereClauses}from'./chunk-HLSB2MCK.js';export{b as KyroPubSub,c as KyroWSServer,a as PubSub,d as createWSServer}from'./chunk-GKYEJ2UF.js';import'./chunk-PP5S2UBV.js';export{c as DrizzleAdapter,b as collectionToDrizzleSchema,f as createDatabase,d as createDrizzleAdapter,a as fieldToDrizzleType,g as runMigrations,h as seedDefaultRoles}from'./chunk-DKESD4HI.js';import {a as a$3}from'./chunk-RHCWCG3O.js';export{a as PostgresAuthAdapter}from'./chunk-RHCWCG3O.js';import'./chunk-OG7CNQGU.js';export{a as MongoDBAdapter,b as createMongoDBAdapter}from'./chunk-VGQ4VUG6.js';import {a as a$1}from'./chunk-GXVCCKOL.js';export{a as MongoDBAuthAdapter}from'./chunk-GXVCCKOL.js';import {a as a$4}from'./chunk-5KOQYQEE.js';export{a as AbstractBaseAdapter}from'./chunk-5KOQYQEE.js';import {a}from'./chunk-6SPPR5JZ.js';import'./chunk-4RMFCTWH.js';import'./chunk-KDNYHLD2.js';import'./chunk-5J6HXUF6.js';import W,{randomBytes}from'crypto';import {readFileSync}from'fs';import Me,{join,resolve}from'path';import {z as z$1}from'zod';export{z}from'zod';import {createStorage}from'unstorage';import Xr from'unstorage/drivers/indexedb';import to from'unstorage/drivers/fs';async function Re(s,e){let t=e.data;for(let r of s){let o=await r({...e,data:t});o!==void 0&&(t=o);}return t}async function Rr(s,e){return Re(s,e)}var R=class extends a$4{connectionString;constructor(e){super(),this.connectionString=e.connectionString;}async connect(){this.connected=true;}async disconnect(){this.connected=false;}async query(e,t=[]){if(!this.connectionString)throw new Error("NeonAdapter: Connection string is required.");try{let r=await fetch(`${this.connectionString}/sql`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:e,params:t})});return r.ok?(await r.json()).rows||[]:[]}catch{return []}}async find(e){return {docs:[],totalDocs:0,limit:e.limit||10,totalPages:1,page:e.page||1,hasNextPage:false,hasPrevPage:false}}async findByID(e){return null}async create(e){return e.data}async update(e){return e.data}async delete(e){return {success:true,id:e.id}}async count(e){return 0}async findOne(e){return null}async findVersions(e){return {docs:[],totalDocs:0,limit:10,totalPages:1,page:1,hasNextPage:false,hasPrevPage:false}}async findVersionByID(e){return null}async createVersion(e){return {id:"v1",parentId:e.documentId,version:e.version||1,snapshot:e.snapshot||{},createdAt:new Date().toISOString()}}async updateLatestVersion(e){return {id:"v1",parentId:e.documentId,version:e.version||1,snapshot:e.snapshot||{},createdAt:new Date().toISOString()}}async deleteVersions(e){}};function ve(s){return new R(s)}var v=class extends a$4{url;authToken;constructor(e){super(),this.url=e.url.replace(/^libsql:\/\//,"https://"),this.authToken=e.authToken;}async connect(){this.connected=true;}async disconnect(){this.connected=false;}async query(e,t=[]){if(!this.url)throw new Error("TursoAdapter: Database URL is required.");try{let r={"Content-Type":"application/json"};this.authToken&&(r.Authorization=`Bearer ${this.authToken}`);let o=await fetch(`${this.url}/v2/pipeline`,{method:"POST",headers:r,body:JSON.stringify({requests:[{type:"execute",stmt:{sql:e,args:t.map(c=>({type:"text",value:String(c)}))}},{type:"close"}]})});if(!o.ok)return [];let i=(await o.json())?.results?.[0]?.response?.result;if(!i||!i.rows)return [];let a=i.cols.map(c=>c.name);return i.rows.map(c=>{let l={};return a.forEach((d,u)=>{l[d]=c[u]?.value??null;}),l})}catch{return []}}async find(e){return {docs:[],totalDocs:0,limit:e.limit||10,totalPages:1,page:e.page||1,hasNextPage:false,hasPrevPage:false}}async findByID(e){return null}async create(e){return e.data}async update(e){return e.data}async delete(e){return {success:true,id:e.id}}async count(e){return 0}async findOne(e){return null}async findVersions(e){return {docs:[],totalDocs:0,limit:10,totalPages:1,page:1,hasNextPage:false,hasPrevPage:false}}async findVersionByID(e){return null}async createVersion(e){return {id:"v1",parentId:e.documentId,version:e.version||1,snapshot:e.snapshot||{},createdAt:new Date().toISOString()}}async updateLatestVersion(e){return {id:"v1",parentId:e.documentId,version:e.version||1,snapshot:e.snapshot||{},createdAt:new Date().toISOString()}}async deleteVersions(e){}};function De(s){return new v(s)}var vr={maxAttempts:5,lockDuration:9e5,notifyUser:true,notifyAdmin:true,adminNotifyAfter:3},x=class{redis;prefix;config;constructor(e,t={},r="kyro:lockout:"){this.redis=e,this.prefix=r,this.config={...vr,...t};}lockKey(e){return `${this.prefix}${e}`}historyKey(e){return `${this.prefix}${e}:history`}async checkLockout(e){let t=this.lockKey(e),r=await this.redis.hgetall(t);if(!r||Object.keys(r).length===0)return {locked:false,attemptsRemaining:this.config.maxAttempts,totalAttempts:0};let o=parseInt(r.attempts,10),n=r.lockedUntil?new Date(parseInt(r.lockedUntil,10)):void 0;return n&&n>new Date?{locked:true,attemptsRemaining:0,lockedUntil:n,totalAttempts:o}:n&&n<=new Date?(await this.unlockAccount(e),{locked:false,attemptsRemaining:this.config.maxAttempts,totalAttempts:0}):{locked:false,attemptsRemaining:Math.max(0,this.config.maxAttempts-o),totalAttempts:o}}async recordFailedAttempt(e){let t=this.lockKey(e),r=this.historyKey(e),o=Date.now(),n=await this.redis.hincrby(t,"attempts",1);if(await this.redis.hset(t,"lastAttempt",o.toString()),await this.redis.lpush(r,o.toString()),await this.redis.ltrim(r,0,99),n>=this.config.maxAttempts){let i=new Date(o+this.config.lockDuration);return await this.redis.hset(t,{lockedAt:o.toString(),lockedUntil:i.getTime().toString()}),await this.redis.expire(t,Math.ceil(this.config.lockDuration/1e3)+3600),{locked:true,attemptsRemaining:0,lockedUntil:i,totalAttempts:n}}return {locked:false,attemptsRemaining:Math.max(0,this.config.maxAttempts-n),totalAttempts:n}}async lockAccount(e,t){let r=this.lockKey(e),o=Date.now(),n=t||this.config.lockDuration,i=new Date(o+n),a=this.redis.pipeline();a.hset(r,{attempts:this.config.maxAttempts.toString(),lockedAt:o.toString(),lockedUntil:i.getTime().toString()}),a.expire(r,Math.ceil(n/1e3)+3600),await a.exec();}async unlockAccount(e){let t=this.lockKey(e);await this.redis.del(t);}async resetAttempts(e){let t=this.lockKey(e);(await this.redis.hgetall(t)).lockedAt?await this.redis.hset(t,{attempts:"0",lockedAt:"",lockedUntil:""}):await this.redis.del(t);}async getLockoutHistory(e,t=10){let r=this.historyKey(e);return (await this.redis.lrange(r,0,t-1)).map(n=>new Date(parseInt(n,10)))}async getLockoutStats(e){let t=this.historyKey(e),r=await this.redis.lrange(t,0,-1),o=r.filter((i,a)=>(a+1)%this.config.maxAttempts===0).length,n=await this.redis.hget(this.lockKey(e),"lockedAt");return {totalFailedAttempts:r.length,lockoutCount:o,lastLockout:n?new Date(parseInt(n,10)):null,averageAttemptsBeforeLockout:o>0?this.config.maxAttempts:0}}shouldNotifyAdmin(e){return this.config.notifyAdmin&&e>=this.config.adminNotifyAfter}getConfig(){return {...this.config}}setConfig(e){this.config={...this.config,...e};}};var Dr={"auth:login":{window:9e5,max:5},"auth:register":{window:36e5,max:3},"auth:forgot":{window:36e5,max:3},"auth:reset":{window:36e5,max:5},"auth:verify":{window:36e5,max:5},"api:general":{window:6e4,max:100},"api:authenticated":{window:6e4,max:200}},P=class{redis;prefix;limits;userLimits;constructor(e,t,r,o="kyro:ratelimit:"){this.redis=e,this.prefix=o,this.limits={...Dr,...t},this.userLimits=r||{"user:api":{window:6e4,max:500},"user:write":{window:36e5,max:100}};}getKey(e,t){return `${this.prefix}${e}:${t}`}async check(e,t){let r=this.limits[e]||this.limits["api:general"],o=this.getKey(e,t),n=Date.now(),i=n-r.window,a=this.redis.pipeline();a.zremrangebyscore(o,0,i),a.zcard(o),a.zadd(o,n,`${n}:${Math.random()}`),a.expire(o,Math.ceil(r.window/1e3)+1);let l=(await a.exec())?.[1]?.[1]||0;if(l>=r.max){let d=await this.redis.zrange(o,0,0,"WITHSCORES"),u=d.length>1?parseInt(d[1],10)+r.window:n+r.window;return {allowed:false,remaining:0,resetAt:u,retryAfter:Math.ceil((u-n)/1e3)}}return {allowed:true,remaining:r.max-l-1,resetAt:n+r.window}}async checkUser(e,t,r){let o=this.userLimits[e]||this.userLimits["user:api"],n=this.getKey(`user:${e}:${t}`,r),i=Date.now(),a=i-o.window,c=this.redis.pipeline();c.zremrangebyscore(n,0,a),c.zcard(n),c.zadd(n,i,`${i}:${Math.random()}`),c.expire(n,Math.ceil(o.window/1e3)+1);let d=(await c.exec())?.[1]?.[1]||0;if(d>=o.max){let u=await this.redis.zrange(n,0,0,"WITHSCORES"),p=u.length>1?parseInt(u[1],10)+o.window:i+o.window;return {allowed:false,remaining:0,resetAt:p,retryAfter:Math.ceil((p-i)/1e3)}}return {allowed:true,remaining:o.max-d-1,resetAt:i+o.window}}async reset(e,t){let r=this.getKey(e,t);await this.redis.del(r);}async resetUser(e,t,r){let o=this.getKey(`user:${e}:${t}`,r);await this.redis.del(o);}async getStatus(e,t){let r=this.limits[e]||this.limits["api:general"],o=this.getKey(e,t),n=Date.now(),i=n-r.window;await this.redis.zremrangebyscore(o,0,i);let a=await this.redis.zcard(o);return {count:a,limit:r.max,remaining:Math.max(0,r.max-a),resetAt:n+r.window}}setLimit(e,t){this.limits[e]=t;}setUserLimit(e,t){this.userLimits[e]=t;}};var T=class{users=new Map;sessions=new Map;refreshTokens=new Map;emailToUserId=new Map;passwordHistory=new Map;emailVerificationTokens=new Map;passwordResetTokens=new Map;auditLogs=[];externalDb=false;constructor(){}async connect(){}async disconnect(){this.users.clear(),this.sessions.clear(),this.refreshTokens.clear(),this.emailToUserId.clear(),this.passwordHistory.clear();}async createUser(e){let t=randomBytes(16).toString("hex"),r=new Date().toISOString(),o=await this.hashPassword(e.password),n={id:t,email:e.email.toLowerCase(),passwordHash:o,role:e.role||"customer",tenantId:e.tenantId,createdAt:r,updatedAt:r};return this.users.set(t,n),this.emailToUserId.set(e.email.toLowerCase(),t),this.passwordHistory.set(t,[]),n}async findUserByEmail(e){let t=this.emailToUserId.get(e.toLowerCase());return t?this.findUserById(t):null}async findUserById(e){return this.users.get(e)||null}async updateUser(e,t){let r=await this.findUserById(e);if(!r)return null;let o={...r,...t,id:e,updatedAt:new Date().toISOString()};return t.email&&t.email!==r.email&&(this.emailToUserId.delete(r.email.toLowerCase()),this.emailToUserId.set(t.email.toLowerCase(),e)),this.users.set(e,o),o}async deleteUser(e){let t=await this.findUserById(e);return t?(this.users.delete(e),this.emailToUserId.delete(t.email.toLowerCase()),this.refreshTokens.forEach((r,o)=>{this.sessions.get(r)?.userId===e&&(this.refreshTokens.delete(o),this.sessions.delete(r));}),this.passwordHistory.delete(e),this.sessions.forEach((r,o)=>{r.userId===e&&this.sessions.delete(o);}),true):false}async hashPassword(e){return (await import('bcryptjs')).default.hash(e,12)}async verifyPassword(e,t){let r=await this.findUserByEmail(e);return !r||!r.passwordHash?null:await(await import('bcryptjs')).default.compare(t,r.passwordHash)?r:null}async createSession(e,t={}){let r=randomBytes(32).toString("hex"),o=randomBytes(32).toString("base64url"),n=randomBytes(32).toString("base64url"),i=new Date,a={id:r,userId:e,token:o,refreshToken:n,expiresAt:new Date(i.getTime()+86400*1e3).toISOString(),createdAt:i.toISOString(),ipAddress:t.ipAddress,userAgent:t.userAgent};return this.sessions.set(r,a),this.refreshTokens.set(n,r),a}async findSessionByToken(e){return this.sessions.get(e)||null}async findSessionByRefreshToken(e){let t=this.refreshTokens.get(e);return t&&this.sessions.get(t)||null}async deleteSession(e){let t=this.sessions.get(e);return t?(t.refreshToken&&this.refreshTokens.delete(t.refreshToken),this.sessions.delete(e),true):false}async deleteUserSessions(e){let t=0;return this.sessions.forEach((r,o)=>{r.userId===e&&(r.refreshToken&&this.refreshTokens.delete(r.refreshToken),this.sessions.delete(o),t++);}),t}async addPasswordToHistory(e,t){let r=this.passwordHistory.get(e)||[];r.push(t),r.length>5&&r.splice(0,r.length-5),this.passwordHistory.set(e,r);}async getPasswordHistory(e,t=5){return this.passwordHistory.get(e)||[]}async isPasswordInHistory(e,t,r=5){let o=await this.getPasswordHistory(t,r),n=(await import('bcryptjs')).default;for(let i of o)if(await n.compare(e,i))return true;return false}async createEmailVerificationToken(e){let t=randomBytes(32).toString("hex"),r=new Date(Date.now()+1440*60*1e3);return this.emailVerificationTokens.set(t,{userId:e,expiresAt:r}),{token:t,expiresAt:r}}async verifyEmailToken(e){let t=this.emailVerificationTokens.get(e);return !t||t.expiresAt<new Date?(this.emailVerificationTokens.delete(e),{success:false,error:"Invalid or expired token"}):(this.emailVerificationTokens.delete(e),{success:true,userId:t.userId})}async createPasswordResetToken(e){let t=await this.findUserByEmail(e);if(!t)return {token:"",expiresAt:new Date,error:"User not found"};let r=randomBytes(32).toString("hex"),o=new Date(Date.now()+3600*1e3);return this.passwordResetTokens.set(r,{userId:t.id,expiresAt:o}),{token:r,expiresAt:o}}async resetPasswordWithToken(e,t){let r=this.passwordResetTokens.get(e);if(!r||r.expiresAt<new Date)return this.passwordResetTokens.delete(e),{success:false,error:"Invalid or expired token"};let o=await this.hashPassword(t);return await this.updateUser(r.userId,{passwordHash:o}),this.passwordResetTokens.delete(e),{success:true}}async hasAnyUsers(){return this.users.size>0}async findAuditLogs(e){let{limit:t=50,offset:r=0}=e,o=this.auditLogs.slice().reverse();return e.userId&&(o=o.filter(n=>n.userId===e.userId)),e.action&&(Array.isArray(e.action)?o=o.filter(n=>e.action.includes(String(n.action))):o=o.filter(n=>n.action===e.action)),e.resource&&(o=o.filter(n=>n.resource===e.resource)),e.success!==void 0&&(o=o.filter(n=>n.success===e.success)),{logs:o.slice(r,r+t),total:o.length}}async createAuditLog(e){let t=randomBytes(16).toString("hex"),o={...e,id:t,timestamp:new Date};return this.auditLogs.push(o),o}};var k=class{storage=new Map;history=new Map;config;constructor(e={}){this.config={maxAttempts:5,lockDuration:9e5,notifyUser:true,notifyAdmin:true,adminNotifyAfter:3,...e};}async checkLockout(e){let t=Date.now(),r=this.storage.get(e);if(r&&r.lockedUntil!==null&&r.lockedUntil<=t)return await this.resetAttempts(e),{locked:false,attemptsRemaining:this.config.maxAttempts,totalAttempts:0};if(!r)return {locked:false,attemptsRemaining:this.config.maxAttempts,totalAttempts:0};let{attempts:o,lockedUntil:n}=r;return n!==null&&n>t?{locked:true,attemptsRemaining:0,lockedUntil:new Date(n),totalAttempts:o}:{locked:false,attemptsRemaining:Math.max(0,this.config.maxAttempts-o),totalAttempts:o}}async recordFailedAttempt(e){let t=Date.now(),r=this.storage.get(e)||{attempts:0,lastAttempt:null,lockedAt:null,lockedUntil:null};r.attempts+=1,r.lastAttempt=t;let o=this.history.get(e)||[];if(o.push(t),o.length>100&&o.splice(0,o.length-100),this.history.set(e,o),this.storage.set(e,r),r.attempts>=this.config.maxAttempts){let n=new Date(t+this.config.lockDuration);return r.lockedAt=t,r.lockedUntil=n.getTime(),this.storage.set(e,r),{locked:true,attemptsRemaining:0,lockedUntil:n,totalAttempts:r.attempts}}return {locked:false,attemptsRemaining:Math.max(0,this.config.maxAttempts-r.attempts),totalAttempts:r.attempts}}async lockAccount(e,t){let r=Date.now(),o=t||this.config.lockDuration,n=new Date(r+o),i=this.storage.get(e)||{attempts:0,lastAttempt:null,lockedAt:null,lockedUntil:null};i.attempts=this.config.maxAttempts,i.lockedAt=r,i.lockedUntil=n.getTime(),this.storage.set(e,i);}async unlockAccount(e){await this.resetAttempts(e);}async resetAttempts(e){let t=this.storage.get(e);t&&(t.attempts=0,t.lockedAt=null,t.lockedUntil=null,this.storage.set(e,t)),this.history.delete(e);}async getLockoutHistory(e,t=10){return (this.history.get(e)||[]).slice(-t).reverse().map(o=>new Date(o))}async getLockoutStats(e){let r=(this.history.get(e)||[]).length,o=Math.floor(r/this.config.maxAttempts),n=null,i=this.storage.get(e);i&&i.lockedAt!==null&&(n=new Date(i.lockedAt));let a=o>0?this.config.maxAttempts:0;return {totalFailedAttempts:r,lockoutCount:o,lastLockout:n,averageAttemptsBeforeLockout:a}}shouldNotifyAdmin(e){return this.config.notifyAdmin&&e>=this.config.adminNotifyAfter}getConfig(){return {...this.config}}setConfig(e){this.config={...this.config,...e};}};function h(s,e=""){return process.env[s]||e}function A(s,e=false){let t=process.env[s];return t?t.toLowerCase()==="true":e}function g(s,e=0){let t=process.env[s];return t?parseInt(t,10):e}function Ie(){let s=process.env.KYRO_AUTH_DATABASE?.toLowerCase();if(s&&["sqlite","postgres","mongodb","memory"].includes(s))return s;try{let e=join(process.cwd(),"kyro.config.ts"),t=readFileSync(e,"utf8");if(t.includes("createLocalAdapter"))return "sqlite";if(t.includes("createDrizzleAdapter"))return t.includes("postgres")||t.includes("postgresql"),"postgres";if(t.includes("createMongoDBAdapter"))return "mongodb"}catch{}return "memory"}async function Er(s){let e=process.cwd(),t=e.endsWith("admin")?join(e,".."):e,r=resolve(t,"data","auth.db");switch(s){case "sqlite":return new a$2({path:h("KYRO_AUTH_DB_PATH",r)});case "postgres":{let o=h("DATABASE_URL","");if(o){let n,i;try{n=(await import('drizzle-orm/postgres-js')).drizzle,i=await import('postgres');}catch{a(["postgres","drizzle-orm"]),n=(await import('drizzle-orm/postgres-js')).drizzle,i=await import('postgres');}let a$1=i.default(o,{onnotice:()=>{}}),c=n(a$1);return new a$3({db:c})}return new a$2({path:h("KYRO_AUTH_DB_PATH",r)})}case "mongodb":{let o=h("MONGODB_URI","");if(o){let n;try{n=(await import('mongodb')).MongoClient;}catch{a(["mongodb"]),n=(await import('mongodb')).MongoClient;}let i=new n(o);await i.connect();let c=new URL(o).pathname.replace(/^\//,"")||"kyro_cms",l=i.db(c);return new a$1({db:l})}return new a$2({path:h("KYRO_AUTH_DB_PATH",r)})}default:return new T}}async function $(s,e){let t=A("KYRO_DISTRIBUTED",false),r;if(t){let{RedisAuthAdapter:u}=await import('./redis-adapter-NN3H4GRX.js'),p=h("REDIS_URL","redis://localhost:6379"),y=A("REDIS_TLS",false),m=new u({url:p,tls:y});await m.connect?.(),r=m;}else {let u=s||Ie();r=await Er(u),r.connect&&await r.connect();}let o=e?await b.fromConfig(e).catch(()=>null)||b.fromEnv()||void 0:b.fromEnv()||void 0,n$1=new c({minLength:g("PASSWORD_MIN_LENGTH",12),requireUppercase:A("PASSWORD_REQUIRE_UPPERCASE",true),requireLowercase:A("PASSWORD_REQUIRE_LOWERCASE",true),requireNumbers:A("PASSWORD_REQUIRE_NUMBERS",true),requireSpecialChars:A("PASSWORD_REQUIRE_SPECIAL",true),preventReuse:g("PASSWORD_PREVENT_REUSE",5),maxLength:g("PASSWORD_MAX_LENGTH",128)}),i,a,c$1;if(t){let p=r.redis;i=new x(p,{maxAttempts:g("LOCKOUT_MAX_ATTEMPTS",5),lockDuration:g("LOCKOUT_DURATION_MINUTES",15)*60*1e3}),a=new P(p,{"auth:login":{window:g("RATE_LIMIT_AUTH_WINDOW_MS",9e5),max:g("RATE_LIMIT_AUTH_MAX_REQUESTS",10)},"api:general":{window:g("RATE_LIMIT_WINDOW_MS",6e4),max:g("RATE_LIMIT_MAX_REQUESTS",100)}}),c$1=new n(p,g("AUDIT_LOG_RETENTION_DAYS",30));}else i=new k({maxAttempts:g("LOCKOUT_MAX_ATTEMPTS",5),lockDuration:g("LOCKOUT_DURATION_MINUTES",15)*60*1e3}),a=new m({"auth:login":{window:g("RATE_LIMIT_AUTH_WINDOW_MS",9e5),max:g("RATE_LIMIT_AUTH_MAX_REQUESTS",10)},"api:general":{window:g("RATE_LIMIT_WINDOW_MS",6e4),max:g("RATE_LIMIT_MAX_REQUESTS",100)}}),c$1=A("AUDIT_LOG_ENABLED",true)?new p(g("AUDIT_LOG_RETENTION_DAYS",30)):void 0;let l=new q$1({redis:r,email:o,jwtSecret:h("APP_SECRET","change-me"),jwtExpiresIn:h("JWT_EXPIRES_IN","24h"),jwtIssuer:h("JWT_ISSUER","kyro-cms"),jwtAudience:h("JWT_AUDIENCE","kyro-cms-client"),passwordPolicy:n$1,lockout:i,rateLimiter:a,auditLogger:c$1,baseUrl:h("EMAIL_BASE_URL","http://localhost:4321"),emailVerificationRequired:A("EMAIL_VERIFICATION_REQUIRED",true)}),d=t?"distributed":s||Ie();return {authAdapter:r,databaseType:d,email:o,passwordPolicy:n$1,lockout:i,rateLimiter:a,auditLogger:c$1,routes:l}}var Ee=$().catch(s=>(console.warn("[AuthConfig] Failed to initialize auth config:",s.message),null));var Or=12,Ur="24h",Vr="7d",U=class{adapter;config;constructor(e,t){this.adapter=e,this.config={secret:t.secret,expiresIn:t.expiresIn??Ur,refreshExpiresIn:t.refreshExpiresIn??Vr,issuer:t.issuer??"kyro-cms",audience:t.audience??[],saltRounds:t.saltRounds??Or};}async register(e){try{if(await this.adapter.findUserByEmail(e.email))return {success:!1,error:"Email already registered"};let r=await this.adapter.createUser({email:e.email,password:e.password,role:e.role??"customer",tenantId:e.tenantId});return this.createSessionForUser(r)}catch(t){return {success:false,error:String(t)}}}async login(e){try{let t=await this.adapter.verifyPassword(e.email,e.password);return t?this.createSessionForUser(t):{success:!1,error:"Invalid credentials"}}catch(t){return {success:false,error:String(t)}}}async logout(e){await this.adapter.deleteSession(e);}async refreshToken(e){try{let t=await this.adapter.findSessionByToken(e);if(!t||new Date(t.expiresAt)<new Date)return {success:!1,error:"Invalid or expired refresh token"};let r=await this.adapter.findUserById(t.userId);return r?(await this.adapter.deleteSession(e),this.createSessionForUser(r)):{success:!1,error:"User not found"}}catch(t){return {success:false,error:String(t)}}}async verifyToken(e){try{let{default:t}=await import('jsonwebtoken');return t.verify(e,this.config.secret,{issuer:this.config.issuer,audience:this.config.audience.length>0?this.config.audience[0]:void 0})}catch{return null}}async getUserFromToken(e){let t=await this.verifyToken(e);return t?this.adapter.findUserById(t.sub):null}async changePassword(e,t,r){try{let o=await this.adapter.findUserById(e);return o?await this.adapter.verifyPassword(o.email,t)?(await this.adapter.updateUser(e,{password:r}),await this.adapter.deleteUserSessions(e),{success:!0,user:o}):{success:!1,error:"Current password is incorrect"}:{success:!1,error:"User not found"}}catch(o){return {success:false,error:String(o)}}}async resetPassword(e,t){try{let r=await this.adapter.findUserByEmail(e);return r?(await this.adapter.updateUser(r.id,{password:t}),await this.adapter.deleteUserSessions(r.id),{success:!0,user:r}):{success:!1,error:"User not found"}}catch(r){return {success:false,error:String(r)}}}async sendEmailVerification(e){try{let{token:t,expiresAt:r}=await this.adapter.createEmailVerificationToken(e);return {success:!0}}catch(t){return {success:false,error:String(t)}}}async verifyEmail(e){try{return await this.adapter.verifyEmailToken(e)}catch(t){return {success:false,error:String(t)}}}async requestPasswordReset(e){try{let t=await this.adapter.createPasswordResetToken(e);return t.error?{success:!1,error:t.error}:{success:!0}}catch(t){return {success:false,error:String(t)}}}async resetPasswordWithToken(e,t){try{return await this.adapter.resetPasswordWithToken(e,t)}catch(r){return {success:false,error:String(r)}}}async deleteAccount(e){try{return await this.adapter.findUserById(e)?(await this.adapter.deleteUserSessions(e),await this.adapter.deleteUser(e),{success:!0}):{success:!1,error:"User not found"}}catch(t){return {success:false,error:String(t)}}}async createSessionForUser(e){let t=await this.generateToken(e),r=await this.adapter.createSession(e.id);return {success:true,user:e,session:r,token:t}}async generateToken(e){let{default:t}=await import('jsonwebtoken'),r={sub:e.id,email:e.email,role:e.role,tenantId:e.tenantId},o={expiresIn:this.parseExpiresIn(this.config.expiresIn)/1e3,issuer:this.config.issuer};return this.config.audience.length>0&&(o.audience=this.config.audience[0]),t.sign(r,this.config.secret,o)}async hashPassword(e){let{default:t}=await import('bcryptjs');return t.hash(e,this.config.saltRounds)}parseExpiresIn(e){if(typeof e=="number")return e;let t=e.match(/^(\d+)([smhd])$/);if(!t)return 864e5;let r=parseInt(t[1],10);switch(t[2]){case "s":return r*1e3;case "m":return r*6e4;case "h":return r*36e5;case "d":return r*864e5;default:return 864e5}}};function _r(s,e){return new U(s,e)}function V(){return {enabled:true,draftsEnabled:true,publishEnabled:true,scheduleEnabled:false,versioningEnabled:true,maxVersionsPerDocument:50,autoPublish:false,requirePublishPermission:true}}var _=class{adapter;config;constructor(e,t){this.adapter=e,this.config={...V(),...t};}async createVersion(e){let r=((await this.adapter.getLatestVersion(e.collection,e.documentId))?.version??0)+1,o={...e,version:r},n=await this.adapter.createVersion(o);return this.config.maxVersionsPerDocument>0&&await this.pruneOldVersions(e.collection,e.documentId),n}async publishVersion(e){let t=await this.adapter.getVersion(e.collection,e.versionId);if(!t)throw new Error("Version not found");if(t.status==="published")throw new Error("Version is already published");await this.adapter.publishVersion(e);}async unpublishDocument(e,t){let r=await this.adapter.getVersions({collection:e,documentId:t,limit:1e3});for(let o of r)if(o.status==="published"){await this.createVersion({collection:e,documentId:t,data:o.data,status:"draft",createdBy:"system",changeDescription:"Unpublished document"});break}}async revertToVersion(e,t,r,o){if(!await this.adapter.getVersion(e,r))throw new Error("Version not found");return await this.adapter.revertToVersion({collection:e,documentId:t,versionId:r,userId:o})}async getVersionHistory(e,t,r=20,o=0){return this.adapter.getVersions({collection:e,documentId:t,limit:r,offset:o})}async compareTwoVersions(e,t,r,o){return this.adapter.compareVersions({collection:e,documentId:t,versionA:r,versionB:o})}async getLatestDraft(e,t){return this.adapter.getLatestVersion(e,t)}async getPublishedVersion(e,t){return this.adapter.getPublishedVersion(e,t)}async getVersion(e,t){return this.adapter.getVersion(e,t)}async schedulePublish(e,t,r,o){if(!this.config.scheduleEnabled)throw new Error("Scheduled publishing is not enabled");if(!await this.adapter.getVersion(e,r))throw new Error("Version not found")}async deleteVersionHistory(e,t){await this.adapter.deleteVersions(e,t);}async pruneOldVersions(e,t){let r=await this.adapter.getVersions({collection:e,documentId:t,limit:this.config.maxVersionsPerDocument+100});if(r.length<=this.config.maxVersionsPerDocument)return;r.slice(0,this.config.maxVersionsPerDocument);let n=r.slice(this.config.maxVersionsPerDocument);for(let i of n)if(i.status!=="published"){await this.adapter.deleteVersions(e,t);break}}};function Mr(s,e){return new _(s,e)}function Hr(s){return s==="published"}function Fr(s){return s==="draft"}function Nr(s){return s==="archived"}function Br(s){return s?Array.isArray(s)?s:Object.values(s):[]}function Kr(s){return s?Array.isArray(s)?s:Object.values(s):[]}function Oe(s){return {collections:Br(s.collections),globals:Kr(s.globals),adapter:s.adapter,plugins:s.plugins,auth:s.auth,cors:s.cors,admin:s.admin,upload:s.upload,graphQL:s.graphQL,typescript:s.typescript,localization:s.localization,rateLimit:s.rateLimit,debug:s.debug}}var $r=Oe;function zr(s){let{siteSettings:e,seoSettings:t,title:r,description:o,image:n,url:i}=s;if(!e)return "";let a=e.siteName||"",c=r||t?.defaultTitle||a,l=t?.titleTemplate,d=t?.separator||" | ",u=t?.siteNameInTitle!==false,p=l?l.replace(/\{\{title\}\}/g,c).replace(/\{\{siteName\}\}/g,u?a:"").replace(/\{\{separator\}\}/g,d).replace(/\s+/g," ").trim():c,y=o||t?.defaultDescription||e.siteDescription||"",m=n||e.siteOgImage?.url||"",D=i||e.siteUrl||"",f=`
|
|
1
|
+
export{a as RedisAuthAdapter}from'./chunk-QOCHBPMK.js';export{R as allSettingsGlobals,c as blogCollections,d as blogGlobals,S as coreSettingsGlobals,W as createTemplateConfig,e as ecommerceCollections,f as ecommerceGlobals,g as kitchenSinkCollections,i as mediaCollections,a as minimalCollections,V as templateCollections}from'./chunk-3NC7GXD5.js';export{a as kyro}from'./chunk-PTS33SK5.js';export{s as AnalyticsPlugin,t as CommentsPlugin,a as ConfigValidationError,y as Kyro,p as KyroPlugin,A as LocalAdapter,q as PluginManager,l as Registry,u as ReviewsPlugin,r as SEOPlugin,v as WishlistPlugin,x as applyCollectionOverrides,h as collectionToCreateZod,i as collectionToUpdateZod,j as collectionToWhereZod,g as collectionToZod,z as createKyro,B as createLocalAdapter,o as createRegistry,f as fieldToZod,m as getRegistry,k as globalToZod,w as presetPlugins,n as resetRegistry,b as validateCollection,e as validateConfig,d as validateFields,c as validateGlobal}from'./chunk-QJZQOLRN.js';export{d as autoBootstrap,a as bootstrapAdmin,e as bootstrapWithRetry,c as getBootstrapFromEnv}from'./chunk-OOQGI3T7.js';import'./chunk-NZ35PV5R.js';export{a as CSSGenerator,g as createAdminStyling,d as defaultDarkTheme,h as defaultFieldStyling,c as defaultLightTheme,e as ecommerce2026Theme,f as generateCSSVariables,b as generateTailwindConfig}from'./chunk-UHFDH3PG.js';export{q as ALL_FIELD_TYPES,n as COMPLEX_FIELD_TYPES,p as LAYOUT_FIELD_TYPES,m as PRIMITIVE_FIELD_TYPES,o as RELATIONAL_FIELD_TYPES,d as isArrayField,f as isBlocksField,e as isGroupField,h as isImageField,k as isLayoutField,b as isNumberField,c as isRelationshipField,i as isRichTextField,j as isSelectField,a as isTextField,g as isUploadField,t as normalizeRichTextValue,u as renderRichText,s as richTextStyles}from'./chunk-INB4LNA6.js';import'./chunk-5SEHX7ON.js';export{a as createContext,g as createCountProcedure,d as createCreateProcedure,f as createDeleteProcedure,h as createDynamicRouter,c as createFindByIDProcedure,b as createFindProcedure,i as createKyroServer,e as createUpdateProcedure}from'./chunk-LHW4R367.js';export{c as buildGraphQLSchema,d as createGraphQLSchema}from'./chunk-PP7W5UKL.js';import {l,n,m,p,q as q$1}from'./chunk-YVM5BDRD.js';export{n as AuditLogger,p as InMemoryAuditLogger,m as InMemoryRateLimiter,s as MediaService,o as createAuditContext,t as createHonoApp,e as createLocalStorage,u as createRESTAPI,i as getAppSecret,j as getEncryptionKey,k as getSessionConfig,r as isEdgeRuntime,h as loadSecrets,d as resolveProvider,g as setDbAdapter}from'./chunk-YVM5BDRD.js';import {k as k$1,l as l$1}from'./chunk-6J27P5D6.js';export{j as ConfigService,k as EmailTransport,l as PasswordPolicy,i as getEmailTemplates,g as renderAccountLocked,a as renderBaseLayout,f as renderMagicLink,e as renderPasswordChanged,c as renderResetPassword,h as renderUserInvite,b as renderVerifyEmail,d as renderWelcome}from'./chunk-6J27P5D6.js';import'./chunk-K6WUOU6P.js';import'./chunk-IETGL7WJ.js';import {a as a$2}from'./chunk-IKOXCJYO.js';export{a as SQLiteAuthAdapter}from'./chunk-IKOXCJYO.js';import'./chunk-NRLIGDYF.js';export{e as ALL_WEBHOOK_EVENTS,f as WEBHOOK_COLLECTION,g as WEBHOOK_DELIVERY_COLLECTION,d as WEBHOOK_EVENTS,n as WebhookService,l as buildDeliveryRecord,m as createTestPayload,o as createWebhookService,j as deliverWebhook,k as deliverWithRetry,i as generateWebhookSecret,h as signPayload}from'./chunk-FVZ5RFLO.js';export{a as evaluateAccess,c as getWhereClause,b as mergeWhereClauses}from'./chunk-HLSB2MCK.js';export{b as KyroPubSub,c as KyroWSServer,a as PubSub,d as createWSServer}from'./chunk-GKYEJ2UF.js';import'./chunk-PP5S2UBV.js';export{c as DrizzleAdapter,b as collectionToDrizzleSchema,f as createDatabase,d as createDrizzleAdapter,a as fieldToDrizzleType,g as runMigrations,h as seedDefaultRoles}from'./chunk-DKESD4HI.js';import {a as a$3}from'./chunk-RHCWCG3O.js';export{a as PostgresAuthAdapter}from'./chunk-RHCWCG3O.js';import'./chunk-OG7CNQGU.js';export{a as MongoDBAdapter,b as createMongoDBAdapter}from'./chunk-VGQ4VUG6.js';import {a as a$1}from'./chunk-GXVCCKOL.js';export{a as MongoDBAuthAdapter}from'./chunk-GXVCCKOL.js';import {a as a$4}from'./chunk-5KOQYQEE.js';export{a as AbstractBaseAdapter}from'./chunk-5KOQYQEE.js';import {a}from'./chunk-6SPPR5JZ.js';import'./chunk-4RMFCTWH.js';import'./chunk-KDNYHLD2.js';import'./chunk-5J6HXUF6.js';import W,{randomBytes}from'crypto';import {readFileSync}from'fs';import Me,{join,resolve}from'path';import {z as z$1}from'zod';export{z}from'zod';import {createStorage}from'unstorage';import Xr from'unstorage/drivers/indexedb';import to from'unstorage/drivers/fs';async function Re(s,e){let t=e.data;for(let r of s){let o=await r({...e,data:t});o!==void 0&&(t=o);}return t}async function Rr(s,e){return Re(s,e)}var R=class extends a$4{connectionString;constructor(e){super(),this.connectionString=e.connectionString;}async connect(){this.connected=true;}async disconnect(){this.connected=false;}async query(e,t=[]){if(!this.connectionString)throw new Error("NeonAdapter: Connection string is required.");try{let r=await fetch(`${this.connectionString}/sql`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:e,params:t})});return r.ok?(await r.json()).rows||[]:[]}catch{return []}}async find(e){return {docs:[],totalDocs:0,limit:e.limit||10,totalPages:1,page:e.page||1,hasNextPage:false,hasPrevPage:false}}async findByID(e){return null}async create(e){return e.data}async update(e){return e.data}async delete(e){return {success:true,id:e.id}}async count(e){return 0}async findOne(e){return null}async findVersions(e){return {docs:[],totalDocs:0,limit:10,totalPages:1,page:1,hasNextPage:false,hasPrevPage:false}}async findVersionByID(e){return null}async createVersion(e){return {id:"v1",parentId:e.documentId,version:e.version||1,snapshot:e.snapshot||{},createdAt:new Date().toISOString()}}async updateLatestVersion(e){return {id:"v1",parentId:e.documentId,version:e.version||1,snapshot:e.snapshot||{},createdAt:new Date().toISOString()}}async deleteVersions(e){}};function ve(s){return new R(s)}var v=class extends a$4{url;authToken;constructor(e){super(),this.url=e.url.replace(/^libsql:\/\//,"https://"),this.authToken=e.authToken;}async connect(){this.connected=true;}async disconnect(){this.connected=false;}async query(e,t=[]){if(!this.url)throw new Error("TursoAdapter: Database URL is required.");try{let r={"Content-Type":"application/json"};this.authToken&&(r.Authorization=`Bearer ${this.authToken}`);let o=await fetch(`${this.url}/v2/pipeline`,{method:"POST",headers:r,body:JSON.stringify({requests:[{type:"execute",stmt:{sql:e,args:t.map(c=>({type:"text",value:String(c)}))}},{type:"close"}]})});if(!o.ok)return [];let i=(await o.json())?.results?.[0]?.response?.result;if(!i||!i.rows)return [];let a=i.cols.map(c=>c.name);return i.rows.map(c=>{let l={};return a.forEach((d,u)=>{l[d]=c[u]?.value??null;}),l})}catch{return []}}async find(e){return {docs:[],totalDocs:0,limit:e.limit||10,totalPages:1,page:e.page||1,hasNextPage:false,hasPrevPage:false}}async findByID(e){return null}async create(e){return e.data}async update(e){return e.data}async delete(e){return {success:true,id:e.id}}async count(e){return 0}async findOne(e){return null}async findVersions(e){return {docs:[],totalDocs:0,limit:10,totalPages:1,page:1,hasNextPage:false,hasPrevPage:false}}async findVersionByID(e){return null}async createVersion(e){return {id:"v1",parentId:e.documentId,version:e.version||1,snapshot:e.snapshot||{},createdAt:new Date().toISOString()}}async updateLatestVersion(e){return {id:"v1",parentId:e.documentId,version:e.version||1,snapshot:e.snapshot||{},createdAt:new Date().toISOString()}}async deleteVersions(e){}};function De(s){return new v(s)}var vr={maxAttempts:5,lockDuration:9e5,notifyUser:true,notifyAdmin:true,adminNotifyAfter:3},x=class{redis;prefix;config;constructor(e,t={},r="kyro:lockout:"){this.redis=e,this.prefix=r,this.config={...vr,...t};}lockKey(e){return `${this.prefix}${e}`}historyKey(e){return `${this.prefix}${e}:history`}async checkLockout(e){let t=this.lockKey(e),r=await this.redis.hgetall(t);if(!r||Object.keys(r).length===0)return {locked:false,attemptsRemaining:this.config.maxAttempts,totalAttempts:0};let o=parseInt(r.attempts,10),n=r.lockedUntil?new Date(parseInt(r.lockedUntil,10)):void 0;return n&&n>new Date?{locked:true,attemptsRemaining:0,lockedUntil:n,totalAttempts:o}:n&&n<=new Date?(await this.unlockAccount(e),{locked:false,attemptsRemaining:this.config.maxAttempts,totalAttempts:0}):{locked:false,attemptsRemaining:Math.max(0,this.config.maxAttempts-o),totalAttempts:o}}async recordFailedAttempt(e){let t=this.lockKey(e),r=this.historyKey(e),o=Date.now(),n=await this.redis.hincrby(t,"attempts",1);if(await this.redis.hset(t,"lastAttempt",o.toString()),await this.redis.lpush(r,o.toString()),await this.redis.ltrim(r,0,99),n>=this.config.maxAttempts){let i=new Date(o+this.config.lockDuration);return await this.redis.hset(t,{lockedAt:o.toString(),lockedUntil:i.getTime().toString()}),await this.redis.expire(t,Math.ceil(this.config.lockDuration/1e3)+3600),{locked:true,attemptsRemaining:0,lockedUntil:i,totalAttempts:n}}return {locked:false,attemptsRemaining:Math.max(0,this.config.maxAttempts-n),totalAttempts:n}}async lockAccount(e,t){let r=this.lockKey(e),o=Date.now(),n=t||this.config.lockDuration,i=new Date(o+n),a=this.redis.pipeline();a.hset(r,{attempts:this.config.maxAttempts.toString(),lockedAt:o.toString(),lockedUntil:i.getTime().toString()}),a.expire(r,Math.ceil(n/1e3)+3600),await a.exec();}async unlockAccount(e){let t=this.lockKey(e);await this.redis.del(t);}async resetAttempts(e){let t=this.lockKey(e);(await this.redis.hgetall(t)).lockedAt?await this.redis.hset(t,{attempts:"0",lockedAt:"",lockedUntil:""}):await this.redis.del(t);}async getLockoutHistory(e,t=10){let r=this.historyKey(e);return (await this.redis.lrange(r,0,t-1)).map(n=>new Date(parseInt(n,10)))}async getLockoutStats(e){let t=this.historyKey(e),r=await this.redis.lrange(t,0,-1),o=r.filter((i,a)=>(a+1)%this.config.maxAttempts===0).length,n=await this.redis.hget(this.lockKey(e),"lockedAt");return {totalFailedAttempts:r.length,lockoutCount:o,lastLockout:n?new Date(parseInt(n,10)):null,averageAttemptsBeforeLockout:o>0?this.config.maxAttempts:0}}shouldNotifyAdmin(e){return this.config.notifyAdmin&&e>=this.config.adminNotifyAfter}getConfig(){return {...this.config}}setConfig(e){this.config={...this.config,...e};}};var Dr={"auth:login":{window:9e5,max:5},"auth:register":{window:36e5,max:3},"auth:forgot":{window:36e5,max:3},"auth:reset":{window:36e5,max:5},"auth:verify":{window:36e5,max:5},"api:general":{window:6e4,max:100},"api:authenticated":{window:6e4,max:200}},P=class{redis;prefix;limits;userLimits;constructor(e,t,r,o="kyro:ratelimit:"){this.redis=e,this.prefix=o,this.limits={...Dr,...t},this.userLimits=r||{"user:api":{window:6e4,max:500},"user:write":{window:36e5,max:100}};}getKey(e,t){return `${this.prefix}${e}:${t}`}async check(e,t){let r=this.limits[e]||this.limits["api:general"],o=this.getKey(e,t),n=Date.now(),i=n-r.window,a=this.redis.pipeline();a.zremrangebyscore(o,0,i),a.zcard(o),a.zadd(o,n,`${n}:${Math.random()}`),a.expire(o,Math.ceil(r.window/1e3)+1);let l=(await a.exec())?.[1]?.[1]||0;if(l>=r.max){let d=await this.redis.zrange(o,0,0,"WITHSCORES"),u=d.length>1?parseInt(d[1],10)+r.window:n+r.window;return {allowed:false,remaining:0,resetAt:u,retryAfter:Math.ceil((u-n)/1e3)}}return {allowed:true,remaining:r.max-l-1,resetAt:n+r.window}}async checkUser(e,t,r){let o=this.userLimits[e]||this.userLimits["user:api"],n=this.getKey(`user:${e}:${t}`,r),i=Date.now(),a=i-o.window,c=this.redis.pipeline();c.zremrangebyscore(n,0,a),c.zcard(n),c.zadd(n,i,`${i}:${Math.random()}`),c.expire(n,Math.ceil(o.window/1e3)+1);let d=(await c.exec())?.[1]?.[1]||0;if(d>=o.max){let u=await this.redis.zrange(n,0,0,"WITHSCORES"),p=u.length>1?parseInt(u[1],10)+o.window:i+o.window;return {allowed:false,remaining:0,resetAt:p,retryAfter:Math.ceil((p-i)/1e3)}}return {allowed:true,remaining:o.max-d-1,resetAt:i+o.window}}async reset(e,t){let r=this.getKey(e,t);await this.redis.del(r);}async resetUser(e,t,r){let o=this.getKey(`user:${e}:${t}`,r);await this.redis.del(o);}async getStatus(e,t){let r=this.limits[e]||this.limits["api:general"],o=this.getKey(e,t),n=Date.now(),i=n-r.window;await this.redis.zremrangebyscore(o,0,i);let a=await this.redis.zcard(o);return {count:a,limit:r.max,remaining:Math.max(0,r.max-a),resetAt:n+r.window}}setLimit(e,t){this.limits[e]=t;}setUserLimit(e,t){this.userLimits[e]=t;}};var T=class{users=new Map;sessions=new Map;refreshTokens=new Map;emailToUserId=new Map;passwordHistory=new Map;emailVerificationTokens=new Map;passwordResetTokens=new Map;auditLogs=[];externalDb=false;constructor(){}async connect(){}async disconnect(){this.users.clear(),this.sessions.clear(),this.refreshTokens.clear(),this.emailToUserId.clear(),this.passwordHistory.clear();}async createUser(e){let t=randomBytes(16).toString("hex"),r=new Date().toISOString(),o=await this.hashPassword(e.password),n={id:t,email:e.email.toLowerCase(),passwordHash:o,role:e.role||"customer",tenantId:e.tenantId,createdAt:r,updatedAt:r};return this.users.set(t,n),this.emailToUserId.set(e.email.toLowerCase(),t),this.passwordHistory.set(t,[]),n}async findUserByEmail(e){let t=this.emailToUserId.get(e.toLowerCase());return t?this.findUserById(t):null}async findUserById(e){return this.users.get(e)||null}async updateUser(e,t){let r=await this.findUserById(e);if(!r)return null;let o={...r,...t,id:e,updatedAt:new Date().toISOString()};return t.email&&t.email!==r.email&&(this.emailToUserId.delete(r.email.toLowerCase()),this.emailToUserId.set(t.email.toLowerCase(),e)),this.users.set(e,o),o}async deleteUser(e){let t=await this.findUserById(e);return t?(this.users.delete(e),this.emailToUserId.delete(t.email.toLowerCase()),this.refreshTokens.forEach((r,o)=>{this.sessions.get(r)?.userId===e&&(this.refreshTokens.delete(o),this.sessions.delete(r));}),this.passwordHistory.delete(e),this.sessions.forEach((r,o)=>{r.userId===e&&this.sessions.delete(o);}),true):false}async hashPassword(e){return (await import('bcryptjs')).default.hash(e,12)}async verifyPassword(e,t){let r=await this.findUserByEmail(e);return !r||!r.passwordHash?null:await(await import('bcryptjs')).default.compare(t,r.passwordHash)?r:null}async createSession(e,t={}){let r=randomBytes(32).toString("hex"),o=randomBytes(32).toString("base64url"),n=randomBytes(32).toString("base64url"),i=new Date,a={id:r,userId:e,token:o,refreshToken:n,expiresAt:new Date(i.getTime()+86400*1e3).toISOString(),createdAt:i.toISOString(),ipAddress:t.ipAddress,userAgent:t.userAgent};return this.sessions.set(r,a),this.refreshTokens.set(n,r),a}async findSessionByToken(e){return this.sessions.get(e)||null}async findSessionByRefreshToken(e){let t=this.refreshTokens.get(e);return t&&this.sessions.get(t)||null}async deleteSession(e){let t=this.sessions.get(e);return t?(t.refreshToken&&this.refreshTokens.delete(t.refreshToken),this.sessions.delete(e),true):false}async deleteUserSessions(e){let t=0;return this.sessions.forEach((r,o)=>{r.userId===e&&(r.refreshToken&&this.refreshTokens.delete(r.refreshToken),this.sessions.delete(o),t++);}),t}async addPasswordToHistory(e,t){let r=this.passwordHistory.get(e)||[];r.push(t),r.length>5&&r.splice(0,r.length-5),this.passwordHistory.set(e,r);}async getPasswordHistory(e,t=5){return this.passwordHistory.get(e)||[]}async isPasswordInHistory(e,t,r=5){let o=await this.getPasswordHistory(t,r),n=(await import('bcryptjs')).default;for(let i of o)if(await n.compare(e,i))return true;return false}async createEmailVerificationToken(e){let t=randomBytes(32).toString("hex"),r=new Date(Date.now()+1440*60*1e3);return this.emailVerificationTokens.set(t,{userId:e,expiresAt:r}),{token:t,expiresAt:r}}async verifyEmailToken(e){let t=this.emailVerificationTokens.get(e);return !t||t.expiresAt<new Date?(this.emailVerificationTokens.delete(e),{success:false,error:"Invalid or expired token"}):(this.emailVerificationTokens.delete(e),{success:true,userId:t.userId})}async createPasswordResetToken(e){let t=await this.findUserByEmail(e);if(!t)return {token:"",expiresAt:new Date,error:"User not found"};let r=randomBytes(32).toString("hex"),o=new Date(Date.now()+3600*1e3);return this.passwordResetTokens.set(r,{userId:t.id,expiresAt:o}),{token:r,expiresAt:o}}async resetPasswordWithToken(e,t){let r=this.passwordResetTokens.get(e);if(!r||r.expiresAt<new Date)return this.passwordResetTokens.delete(e),{success:false,error:"Invalid or expired token"};let o=await this.hashPassword(t);return await this.updateUser(r.userId,{passwordHash:o}),this.passwordResetTokens.delete(e),{success:true}}async hasAnyUsers(){return this.users.size>0}async findAuditLogs(e){let{limit:t=50,offset:r=0}=e,o=this.auditLogs.slice().reverse();return e.userId&&(o=o.filter(n=>n.userId===e.userId)),e.action&&(Array.isArray(e.action)?o=o.filter(n=>e.action.includes(String(n.action))):o=o.filter(n=>n.action===e.action)),e.resource&&(o=o.filter(n=>n.resource===e.resource)),e.success!==void 0&&(o=o.filter(n=>n.success===e.success)),{logs:o.slice(r,r+t),total:o.length}}async createAuditLog(e){let t=randomBytes(16).toString("hex"),o={...e,id:t,timestamp:new Date};return this.auditLogs.push(o),o}};var k=class{storage=new Map;history=new Map;config;constructor(e={}){this.config={maxAttempts:5,lockDuration:9e5,notifyUser:true,notifyAdmin:true,adminNotifyAfter:3,...e};}async checkLockout(e){let t=Date.now(),r=this.storage.get(e);if(r&&r.lockedUntil!==null&&r.lockedUntil<=t)return await this.resetAttempts(e),{locked:false,attemptsRemaining:this.config.maxAttempts,totalAttempts:0};if(!r)return {locked:false,attemptsRemaining:this.config.maxAttempts,totalAttempts:0};let{attempts:o,lockedUntil:n}=r;return n!==null&&n>t?{locked:true,attemptsRemaining:0,lockedUntil:new Date(n),totalAttempts:o}:{locked:false,attemptsRemaining:Math.max(0,this.config.maxAttempts-o),totalAttempts:o}}async recordFailedAttempt(e){let t=Date.now(),r=this.storage.get(e)||{attempts:0,lastAttempt:null,lockedAt:null,lockedUntil:null};r.attempts+=1,r.lastAttempt=t;let o=this.history.get(e)||[];if(o.push(t),o.length>100&&o.splice(0,o.length-100),this.history.set(e,o),this.storage.set(e,r),r.attempts>=this.config.maxAttempts){let n=new Date(t+this.config.lockDuration);return r.lockedAt=t,r.lockedUntil=n.getTime(),this.storage.set(e,r),{locked:true,attemptsRemaining:0,lockedUntil:n,totalAttempts:r.attempts}}return {locked:false,attemptsRemaining:Math.max(0,this.config.maxAttempts-r.attempts),totalAttempts:r.attempts}}async lockAccount(e,t){let r=Date.now(),o=t||this.config.lockDuration,n=new Date(r+o),i=this.storage.get(e)||{attempts:0,lastAttempt:null,lockedAt:null,lockedUntil:null};i.attempts=this.config.maxAttempts,i.lockedAt=r,i.lockedUntil=n.getTime(),this.storage.set(e,i);}async unlockAccount(e){await this.resetAttempts(e);}async resetAttempts(e){let t=this.storage.get(e);t&&(t.attempts=0,t.lockedAt=null,t.lockedUntil=null,this.storage.set(e,t)),this.history.delete(e);}async getLockoutHistory(e,t=10){return (this.history.get(e)||[]).slice(-t).reverse().map(o=>new Date(o))}async getLockoutStats(e){let r=(this.history.get(e)||[]).length,o=Math.floor(r/this.config.maxAttempts),n=null,i=this.storage.get(e);i&&i.lockedAt!==null&&(n=new Date(i.lockedAt));let a=o>0?this.config.maxAttempts:0;return {totalFailedAttempts:r,lockoutCount:o,lastLockout:n,averageAttemptsBeforeLockout:a}}shouldNotifyAdmin(e){return this.config.notifyAdmin&&e>=this.config.adminNotifyAfter}getConfig(){return {...this.config}}setConfig(e){this.config={...this.config,...e};}};function h(s,e=""){return process.env[s]||e}function A(s,e=false){let t=process.env[s];return t?t.toLowerCase()==="true":e}function g(s,e=0){let t=process.env[s];return t?parseInt(t,10):e}function Ie(){let s=process.env.KYRO_AUTH_DATABASE?.toLowerCase();if(s&&["sqlite","postgres","mongodb","memory"].includes(s))return s;try{let e=join(process.cwd(),"kyro.config.ts"),t=readFileSync(e,"utf8");if(t.includes("createLocalAdapter"))return "sqlite";if(t.includes("createDrizzleAdapter"))return t.includes("postgres")||t.includes("postgresql"),"postgres";if(t.includes("createMongoDBAdapter"))return "mongodb"}catch{}return "memory"}async function Er(s){let e=process.cwd(),t=e.endsWith("admin")?join(e,".."):e,r=resolve(t,"data","auth.db");switch(s){case "sqlite":return new a$2({path:h("KYRO_AUTH_DB_PATH",r)});case "postgres":{let o=h("DATABASE_URL","");if(o){let n,i;try{n=(await import('drizzle-orm/postgres-js')).drizzle,i=await import('postgres');}catch{a(["postgres","drizzle-orm"]),n=(await import('drizzle-orm/postgres-js')).drizzle,i=await import('postgres');}let a$1=i.default(o,{onnotice:()=>{}}),c=n(a$1);return new a$3({db:c})}return new a$2({path:h("KYRO_AUTH_DB_PATH",r)})}case "mongodb":{let o=h("MONGODB_URI","");if(o){let n;try{n=(await import('mongodb')).MongoClient;}catch{a(["mongodb"]),n=(await import('mongodb')).MongoClient;}let i=new n(o);await i.connect();let c=new URL(o).pathname.replace(/^\//,"")||"kyro_cms",l=i.db(c);return new a$1({db:l})}return new a$2({path:h("KYRO_AUTH_DB_PATH",r)})}default:return new T}}async function $(s,e){let t=A("KYRO_DISTRIBUTED",false),r;if(t){let{RedisAuthAdapter:u}=await import('./redis-adapter-NN3H4GRX.js'),p=h("REDIS_URL","redis://localhost:6379"),y=A("REDIS_TLS",false),m=new u({url:p,tls:y});await m.connect?.(),r=m;}else {let u=s||Ie();r=await Er(u),r.connect&&await r.connect();}let o=e?await k$1.fromConfig(e).catch(()=>null)||k$1.fromEnv()||void 0:k$1.fromEnv()||void 0,n$1=new l$1({minLength:g("PASSWORD_MIN_LENGTH",12),requireUppercase:A("PASSWORD_REQUIRE_UPPERCASE",true),requireLowercase:A("PASSWORD_REQUIRE_LOWERCASE",true),requireNumbers:A("PASSWORD_REQUIRE_NUMBERS",true),requireSpecialChars:A("PASSWORD_REQUIRE_SPECIAL",true),preventReuse:g("PASSWORD_PREVENT_REUSE",5),maxLength:g("PASSWORD_MAX_LENGTH",128)}),i,a,c;if(t){let p=r.redis;i=new x(p,{maxAttempts:g("LOCKOUT_MAX_ATTEMPTS",5),lockDuration:g("LOCKOUT_DURATION_MINUTES",15)*60*1e3}),a=new P(p,{"auth:login":{window:g("RATE_LIMIT_AUTH_WINDOW_MS",9e5),max:g("RATE_LIMIT_AUTH_MAX_REQUESTS",10)},"api:general":{window:g("RATE_LIMIT_WINDOW_MS",6e4),max:g("RATE_LIMIT_MAX_REQUESTS",100)}}),c=new n(p,g("AUDIT_LOG_RETENTION_DAYS",30));}else i=new k({maxAttempts:g("LOCKOUT_MAX_ATTEMPTS",5),lockDuration:g("LOCKOUT_DURATION_MINUTES",15)*60*1e3}),a=new m({"auth:login":{window:g("RATE_LIMIT_AUTH_WINDOW_MS",9e5),max:g("RATE_LIMIT_AUTH_MAX_REQUESTS",10)},"api:general":{window:g("RATE_LIMIT_WINDOW_MS",6e4),max:g("RATE_LIMIT_MAX_REQUESTS",100)}}),c=A("AUDIT_LOG_ENABLED",true)?new p(g("AUDIT_LOG_RETENTION_DAYS",30)):void 0;let l=new q$1({redis:r,email:o,jwtSecret:h("APP_SECRET","change-me"),jwtExpiresIn:h("JWT_EXPIRES_IN","24h"),jwtIssuer:h("JWT_ISSUER","kyro-cms"),jwtAudience:h("JWT_AUDIENCE","kyro-cms-client"),passwordPolicy:n$1,lockout:i,rateLimiter:a,auditLogger:c,baseUrl:h("EMAIL_BASE_URL","http://localhost:4321"),emailVerificationRequired:A("EMAIL_VERIFICATION_REQUIRED",true)}),d=t?"distributed":s||Ie();return {authAdapter:r,databaseType:d,email:o,passwordPolicy:n$1,lockout:i,rateLimiter:a,auditLogger:c,routes:l}}var Ee=$().catch(s=>(console.warn("[AuthConfig] Failed to initialize auth config:",s.message),null));var Or=12,Ur="24h",Vr="7d",U=class{adapter;config;constructor(e,t){this.adapter=e,this.config={secret:t.secret,expiresIn:t.expiresIn??Ur,refreshExpiresIn:t.refreshExpiresIn??Vr,issuer:t.issuer??"kyro-cms",audience:t.audience??[],saltRounds:t.saltRounds??Or};}async register(e){try{if(await this.adapter.findUserByEmail(e.email))return {success:!1,error:"Email already registered"};let r=await this.adapter.createUser({email:e.email,password:e.password,role:e.role??"customer",tenantId:e.tenantId});return this.createSessionForUser(r)}catch(t){return {success:false,error:String(t)}}}async login(e){try{let t=await this.adapter.verifyPassword(e.email,e.password);return t?this.createSessionForUser(t):{success:!1,error:"Invalid credentials"}}catch(t){return {success:false,error:String(t)}}}async logout(e){await this.adapter.deleteSession(e);}async refreshToken(e){try{let t=await this.adapter.findSessionByToken(e);if(!t||new Date(t.expiresAt)<new Date)return {success:!1,error:"Invalid or expired refresh token"};let r=await this.adapter.findUserById(t.userId);return r?(await this.adapter.deleteSession(e),this.createSessionForUser(r)):{success:!1,error:"User not found"}}catch(t){return {success:false,error:String(t)}}}async verifyToken(e){try{let{default:t}=await import('jsonwebtoken');return t.verify(e,this.config.secret,{issuer:this.config.issuer,audience:this.config.audience.length>0?this.config.audience[0]:void 0})}catch{return null}}async getUserFromToken(e){let t=await this.verifyToken(e);return t?this.adapter.findUserById(t.sub):null}async changePassword(e,t,r){try{let o=await this.adapter.findUserById(e);return o?await this.adapter.verifyPassword(o.email,t)?(await this.adapter.updateUser(e,{password:r}),await this.adapter.deleteUserSessions(e),{success:!0,user:o}):{success:!1,error:"Current password is incorrect"}:{success:!1,error:"User not found"}}catch(o){return {success:false,error:String(o)}}}async resetPassword(e,t){try{let r=await this.adapter.findUserByEmail(e);return r?(await this.adapter.updateUser(r.id,{password:t}),await this.adapter.deleteUserSessions(r.id),{success:!0,user:r}):{success:!1,error:"User not found"}}catch(r){return {success:false,error:String(r)}}}async sendEmailVerification(e){try{let{token:t,expiresAt:r}=await this.adapter.createEmailVerificationToken(e);return {success:!0}}catch(t){return {success:false,error:String(t)}}}async verifyEmail(e){try{return await this.adapter.verifyEmailToken(e)}catch(t){return {success:false,error:String(t)}}}async requestPasswordReset(e){try{let t=await this.adapter.createPasswordResetToken(e);return t.error?{success:!1,error:t.error}:{success:!0}}catch(t){return {success:false,error:String(t)}}}async resetPasswordWithToken(e,t){try{return await this.adapter.resetPasswordWithToken(e,t)}catch(r){return {success:false,error:String(r)}}}async deleteAccount(e){try{return await this.adapter.findUserById(e)?(await this.adapter.deleteUserSessions(e),await this.adapter.deleteUser(e),{success:!0}):{success:!1,error:"User not found"}}catch(t){return {success:false,error:String(t)}}}async createSessionForUser(e){let t=await this.generateToken(e),r=await this.adapter.createSession(e.id);return {success:true,user:e,session:r,token:t}}async generateToken(e){let{default:t}=await import('jsonwebtoken'),r={sub:e.id,email:e.email,role:e.role,tenantId:e.tenantId},o={expiresIn:this.parseExpiresIn(this.config.expiresIn)/1e3,issuer:this.config.issuer};return this.config.audience.length>0&&(o.audience=this.config.audience[0]),t.sign(r,this.config.secret,o)}async hashPassword(e){let{default:t}=await import('bcryptjs');return t.hash(e,this.config.saltRounds)}parseExpiresIn(e){if(typeof e=="number")return e;let t=e.match(/^(\d+)([smhd])$/);if(!t)return 864e5;let r=parseInt(t[1],10);switch(t[2]){case "s":return r*1e3;case "m":return r*6e4;case "h":return r*36e5;case "d":return r*864e5;default:return 864e5}}};function _r(s,e){return new U(s,e)}function V(){return {enabled:true,draftsEnabled:true,publishEnabled:true,scheduleEnabled:false,versioningEnabled:true,maxVersionsPerDocument:50,autoPublish:false,requirePublishPermission:true}}var _=class{adapter;config;constructor(e,t){this.adapter=e,this.config={...V(),...t};}async createVersion(e){let r=((await this.adapter.getLatestVersion(e.collection,e.documentId))?.version??0)+1,o={...e,version:r},n=await this.adapter.createVersion(o);return this.config.maxVersionsPerDocument>0&&await this.pruneOldVersions(e.collection,e.documentId),n}async publishVersion(e){let t=await this.adapter.getVersion(e.collection,e.versionId);if(!t)throw new Error("Version not found");if(t.status==="published")throw new Error("Version is already published");await this.adapter.publishVersion(e);}async unpublishDocument(e,t){let r=await this.adapter.getVersions({collection:e,documentId:t,limit:1e3});for(let o of r)if(o.status==="published"){await this.createVersion({collection:e,documentId:t,data:o.data,status:"draft",createdBy:"system",changeDescription:"Unpublished document"});break}}async revertToVersion(e,t,r,o){if(!await this.adapter.getVersion(e,r))throw new Error("Version not found");return await this.adapter.revertToVersion({collection:e,documentId:t,versionId:r,userId:o})}async getVersionHistory(e,t,r=20,o=0){return this.adapter.getVersions({collection:e,documentId:t,limit:r,offset:o})}async compareTwoVersions(e,t,r,o){return this.adapter.compareVersions({collection:e,documentId:t,versionA:r,versionB:o})}async getLatestDraft(e,t){return this.adapter.getLatestVersion(e,t)}async getPublishedVersion(e,t){return this.adapter.getPublishedVersion(e,t)}async getVersion(e,t){return this.adapter.getVersion(e,t)}async schedulePublish(e,t,r,o){if(!this.config.scheduleEnabled)throw new Error("Scheduled publishing is not enabled");if(!await this.adapter.getVersion(e,r))throw new Error("Version not found")}async deleteVersionHistory(e,t){await this.adapter.deleteVersions(e,t);}async pruneOldVersions(e,t){let r=await this.adapter.getVersions({collection:e,documentId:t,limit:this.config.maxVersionsPerDocument+100});if(r.length<=this.config.maxVersionsPerDocument)return;r.slice(0,this.config.maxVersionsPerDocument);let n=r.slice(this.config.maxVersionsPerDocument);for(let i of n)if(i.status!=="published"){await this.adapter.deleteVersions(e,t);break}}};function Mr(s,e){return new _(s,e)}function Hr(s){return s==="published"}function Fr(s){return s==="draft"}function Nr(s){return s==="archived"}function Br(s){return s?Array.isArray(s)?s:Object.values(s):[]}function Kr(s){return s?Array.isArray(s)?s:Object.values(s):[]}function Oe(s){return {collections:Br(s.collections),globals:Kr(s.globals),adapter:s.adapter,plugins:s.plugins,auth:s.auth,cors:s.cors,admin:s.admin,upload:s.upload,graphQL:s.graphQL,typescript:s.typescript,localization:s.localization,rateLimit:s.rateLimit,debug:s.debug}}var $r=Oe;function zr(s){let{siteSettings:e,seoSettings:t,title:r,description:o,image:n,url:i}=s;if(!e)return "";let a=e.siteName||"",c=r||t?.defaultTitle||a,l=t?.titleTemplate,d=t?.separator||" | ",u=t?.siteNameInTitle!==false,p=l?l.replace(/\{\{title\}\}/g,c).replace(/\{\{siteName\}\}/g,u?a:"").replace(/\{\{separator\}\}/g,d).replace(/\s+/g," ").trim():c,y=o||t?.defaultDescription||e.siteDescription||"",m=n||e.siteOgImage?.url||"",D=i||e.siteUrl||"",f=`
|
|
2
2
|
<title>${p}</title>
|
|
3
3
|
<meta name="description" content="${y}">
|
|
4
4
|
`;e.siteFavicon?.url&&(f+=`
|
package/dist/rest/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var chunkXTRY75KC_cjs=require('../chunk-XTRY75KC.cjs');require('../chunk-5K4YG5DA.cjs'),require('../chunk-WIZ6C5QZ.cjs'),require('../chunk-GO34AOBZ.cjs'),require('../chunk-HOP4D5XZ.cjs'),require('../chunk-HVXO3OFB.cjs'),require('../chunk-ILEZ3NYX.cjs'),require('../chunk-NY47CFVP.cjs'),require('../chunk-WG3UQEV7.cjs'),require('../chunk-GYQMNXXW.cjs'),require('../chunk-MIOMMB23.cjs'),require('../chunk-BVG6VSAJ.cjs'),require('../chunk-FHJJKFAU.cjs'),require('../chunk-D5P2IPGX.cjs'),require('../chunk-G7SSHELM.cjs'),require('../chunk-Q3Q7BJVQ.cjs'),require('../chunk-AHSFSERC.cjs');Object.defineProperty(exports,"createHonoApp",{enumerable:true,get:function(){return chunkXTRY75KC_cjs.t}});Object.defineProperty(exports,"createRESTAPI",{enumerable:true,get:function(){return chunkXTRY75KC_cjs.u}});
|
package/dist/rest/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{t as createHonoApp,u as createRESTAPI}from'../chunk-
|
|
1
|
+
export{t as createHonoApp,u as createRESTAPI}from'../chunk-YVM5BDRD.js';import'../chunk-6J27P5D6.js';import'../chunk-K6WUOU6P.js';import'../chunk-IETGL7WJ.js';import'../chunk-IKOXCJYO.js';import'../chunk-NRLIGDYF.js';import'../chunk-FVZ5RFLO.js';import'../chunk-HLSB2MCK.js';import'../chunk-DKESD4HI.js';import'../chunk-RHCWCG3O.js';import'../chunk-OG7CNQGU.js';import'../chunk-GXVCCKOL.js';import'../chunk-5KOQYQEE.js';import'../chunk-6SPPR5JZ.js';import'../chunk-4RMFCTWH.js';import'../chunk-KDNYHLD2.js';import'../chunk-5J6HXUF6.js';
|
package/dist/templates/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var chunkSFAD6WPC_cjs=require('../chunk-SFAD6WPC.cjs'),chunk65G73T7Z_cjs=require('../chunk-65G73T7Z.cjs'),chunkGO34AOBZ_cjs=require('../chunk-GO34AOBZ.cjs');require('../chunk-AHSFSERC.cjs');Object.defineProperty(exports,"accessSettingsGlobal",{enumerable:true,get:function(){return chunkSFAD6WPC_cjs.N}});Object.defineProperty(exports,"allSettingsGlobals",{enumerable:true,get:function(){return chunkSFAD6WPC_cjs.R}});Object.defineProperty(exports,"blogCollections",{enumerable:true,get:function(){return chunkSFAD6WPC_cjs.c}});Object.defineProperty(exports,"blogGlobals",{enumerable:true,get:function(){return chunkSFAD6WPC_cjs.d}});Object.defineProperty(exports,"brandSettingsGlobal",{enumerable:true,get:function(){return chunkSFAD6WPC_cjs.L}});Object.defineProperty(exports,"brandsCollection",{enumerable:true,get:function(){return chunkSFAD6WPC_cjs.H}});Object.defineProperty(exports,"brandsCollections",{enumerable:true,get:function(){return chunkSFAD6WPC_cjs.I}});Object.defineProperty(exports,"categoriesCollection",{enumerable:true,get:function(){return chunkSFAD6WPC_cjs.p}});Object.defineProperty(exports,"categoriesCollections",{enumerable:true,get:function(){return chunkSFAD6WPC_cjs.q}});Object.defineProperty(exports,"coreSettingsGlobals",{enumerable:true,get:function(){return chunkSFAD6WPC_cjs.S}});Object.defineProperty(exports,"couponsCollection",{enumerable:true,get:function(){return chunkSFAD6WPC_cjs.z}});Object.defineProperty(exports,"couponsCollections",{enumerable:true,get:function(){return chunkSFAD6WPC_cjs.A}});Object.defineProperty(exports,"createTemplateConfig",{enumerable:true,get:function(){return chunkSFAD6WPC_cjs.W}});Object.defineProperty(exports,"customersCollection",{enumerable:true,get:function(){return chunkSFAD6WPC_cjs.v}});Object.defineProperty(exports,"customersCollections",{enumerable:true,get:function(){return chunkSFAD6WPC_cjs.w}});Object.defineProperty(exports,"ecommerceCollections",{enumerable:true,get:function(){return chunkSFAD6WPC_cjs.e}});Object.defineProperty(exports,"ecommerceGlobals",{enumerable:true,get:function(){return chunkSFAD6WPC_cjs.f}});Object.defineProperty(exports,"emailSettingsGlobal",{enumerable:true,get:function(){return chunkSFAD6WPC_cjs.M}});Object.defineProperty(exports,"formEntriesCollection",{enumerable:true,get:function(){return chunkSFAD6WPC_cjs.D}});Object.defineProperty(exports,"formEntriesCollections",{enumerable:true,get:function(){return chunkSFAD6WPC_cjs.E}});Object.defineProperty(exports,"formsCollection",{enumerable:true,get:function(){return chunkSFAD6WPC_cjs.B}});Object.defineProperty(exports,"formsCollections",{enumerable:true,get:function(){return chunkSFAD6WPC_cjs.C}});Object.defineProperty(exports,"getSettingsForTemplate",{enumerable:true,get:function(){return chunkSFAD6WPC_cjs.U}});Object.defineProperty(exports,"kitchenSinkCollections",{enumerable:true,get:function(){return chunkSFAD6WPC_cjs.g}});Object.defineProperty(exports,"mediaCollection",{enumerable:true,get:function(){return chunkSFAD6WPC_cjs.h}});Object.defineProperty(exports,"mediaCollections",{enumerable:true,get:function(){return chunkSFAD6WPC_cjs.i}});Object.defineProperty(exports,"menuCollection",{enumerable:true,get:function(){return chunkSFAD6WPC_cjs.j}});Object.defineProperty(exports,"menuCollections",{enumerable:true,get:function(){return chunkSFAD6WPC_cjs.k}});Object.defineProperty(exports,"minimalCollections",{enumerable:true,get:function(){return chunkSFAD6WPC_cjs.a}});Object.defineProperty(exports,"ordersCollection",{enumerable:true,get:function(){return chunkSFAD6WPC_cjs.x}});Object.defineProperty(exports,"ordersCollections",{enumerable:true,get:function(){return chunkSFAD6WPC_cjs.y}});Object.defineProperty(exports,"pageCollection",{enumerable:true,get:function(){return chunkSFAD6WPC_cjs.n}});Object.defineProperty(exports,"pageCollections",{enumerable:true,get:function(){return chunkSFAD6WPC_cjs.o}});Object.defineProperty(exports,"postsCollection",{enumerable:true,get:function(){return chunkSFAD6WPC_cjs.l}});Object.defineProperty(exports,"postsCollections",{enumerable:true,get:function(){return chunkSFAD6WPC_cjs.m}});Object.defineProperty(exports,"productCategoriesCollection",{enumerable:true,get:function(){return chunkSFAD6WPC_cjs.r}});Object.defineProperty(exports,"productCategoriesCollections",{enumerable:true,get:function(){return chunkSFAD6WPC_cjs.s}});Object.defineProperty(exports,"productsCollection",{enumerable:true,get:function(){return chunkSFAD6WPC_cjs.t}});Object.defineProperty(exports,"productsCollections",{enumerable:true,get:function(){return chunkSFAD6WPC_cjs.u}});Object.defineProperty(exports,"reviewsCollection",{enumerable:true,get:function(){return chunkSFAD6WPC_cjs.F}});Object.defineProperty(exports,"reviewsCollections",{enumerable:true,get:function(){return chunkSFAD6WPC_cjs.G}});Object.defineProperty(exports,"seoSettingsGlobal",{enumerable:true,get:function(){return chunkSFAD6WPC_cjs.K}});Object.defineProperty(exports,"settingsBySlug",{enumerable:true,get:function(){return chunkSFAD6WPC_cjs.T}});Object.defineProperty(exports,"shippingSettingsGlobal",{enumerable:true,get:function(){return chunkSFAD6WPC_cjs.P}});Object.defineProperty(exports,"siteSettingsGlobal",{enumerable:true,get:function(){return chunkSFAD6WPC_cjs.J}});Object.defineProperty(exports,"starterCollections",{enumerable:true,get:function(){return chunkSFAD6WPC_cjs.b}});Object.defineProperty(exports,"storeSettingsGlobal",{enumerable:true,get:function(){return chunkSFAD6WPC_cjs.O}});Object.defineProperty(exports,"systemSettingsGlobal",{enumerable:true,get:function(){return chunkSFAD6WPC_cjs.Q}});Object.defineProperty(exports,"templateCollections",{enumerable:true,get:function(){return chunkSFAD6WPC_cjs.V}});Object.defineProperty(exports,"storageSettingsGlobal",{enumerable:true,get:function(){return chunk65G73T7Z_cjs.a}});Object.defineProperty(exports,"authCollections",{enumerable:true,get:function(){return chunkGO34AOBZ_cjs.b}});
|
package/dist/templates/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{N as accessSettingsGlobal,R as allSettingsGlobals,c as blogCollections,d as blogGlobals,L as brandSettingsGlobal,H as brandsCollection,I as brandsCollections,p as categoriesCollection,q as categoriesCollections,S as coreSettingsGlobals,z as couponsCollection,A as couponsCollections,W as createTemplateConfig,v as customersCollection,w as customersCollections,e as ecommerceCollections,f as ecommerceGlobals,M as emailSettingsGlobal,D as formEntriesCollection,E as formEntriesCollections,B as formsCollection,C as formsCollections,U as getSettingsForTemplate,g as kitchenSinkCollections,h as mediaCollection,i as mediaCollections,j as menuCollection,k as menuCollections,a as minimalCollections,x as ordersCollection,y as ordersCollections,n as pageCollection,o as pageCollections,l as postsCollection,m as postsCollections,r as productCategoriesCollection,s as productCategoriesCollections,t as productsCollection,u as productsCollections,F as reviewsCollection,G as reviewsCollections,K as seoSettingsGlobal,T as settingsBySlug,P as shippingSettingsGlobal,J as siteSettingsGlobal,b as starterCollections,O as storeSettingsGlobal,Q as systemSettingsGlobal,V as templateCollections}from'../chunk-
|
|
1
|
+
export{N as accessSettingsGlobal,R as allSettingsGlobals,c as blogCollections,d as blogGlobals,L as brandSettingsGlobal,H as brandsCollection,I as brandsCollections,p as categoriesCollection,q as categoriesCollections,S as coreSettingsGlobals,z as couponsCollection,A as couponsCollections,W as createTemplateConfig,v as customersCollection,w as customersCollections,e as ecommerceCollections,f as ecommerceGlobals,M as emailSettingsGlobal,D as formEntriesCollection,E as formEntriesCollections,B as formsCollection,C as formsCollections,U as getSettingsForTemplate,g as kitchenSinkCollections,h as mediaCollection,i as mediaCollections,j as menuCollection,k as menuCollections,a as minimalCollections,x as ordersCollection,y as ordersCollections,n as pageCollection,o as pageCollections,l as postsCollection,m as postsCollections,r as productCategoriesCollection,s as productCategoriesCollections,t as productsCollection,u as productsCollections,F as reviewsCollection,G as reviewsCollections,K as seoSettingsGlobal,T as settingsBySlug,P as shippingSettingsGlobal,J as siteSettingsGlobal,b as starterCollections,O as storeSettingsGlobal,Q as systemSettingsGlobal,V as templateCollections}from'../chunk-3NC7GXD5.js';export{a as storageSettingsGlobal}from'../chunk-NZ35PV5R.js';export{b as authCollections}from'../chunk-IETGL7WJ.js';import'../chunk-5J6HXUF6.js';
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
'use strict';var chunkQMQXKCCQ_cjs=require('./chunk-QMQXKCCQ.cjs');require('./chunk-GCQTSPX6.cjs'),require('./chunk-WIZ6C5QZ.cjs'),require('./chunk-HOP4D5XZ.cjs'),require('./chunk-AHSFSERC.cjs');Object.defineProperty(exports,"autoBootstrap",{enumerable:true,get:function(){return chunkQMQXKCCQ_cjs.d}});Object.defineProperty(exports,"bootstrapAdmin",{enumerable:true,get:function(){return chunkQMQXKCCQ_cjs.a}});Object.defineProperty(exports,"bootstrapWithRetry",{enumerable:true,get:function(){return chunkQMQXKCCQ_cjs.e}});Object.defineProperty(exports,"checkBootstrapRequired",{enumerable:true,get:function(){return chunkQMQXKCCQ_cjs.b}});Object.defineProperty(exports,"getBootstrapFromEnv",{enumerable:true,get:function(){return chunkQMQXKCCQ_cjs.c}});
|
package/dist/chunk-6NGUY76Y.js
DELETED
|
@@ -1,259 +0,0 @@
|
|
|
1
|
-
import {a}from'./chunk-K6WUOU6P.js';var u=false,p=class n{db;cache={};loaded=false;static SENSITIVE_KEYS=["storage.s3.secret_access_key","storage.r2.secret_access_key","storage.gcs.private_key","storage.backblaze.application_key","storage.wasabi.secret_access_key","storage.ftp.password","storage.bunny.api_key","storage.cloudinary.api_secret","storage.imgix.sign_key","email.smtp.pass","auth.jwt_secret","auth.github_secret","auth.google_secret","auth.app_secret","database.url","redis.url","auth.admin_password"];constructor(e){this.db=e;}async load(){if(!this.loaded){await this.ensureSettingsTable();try{if(typeof this.db?.select=="function"){let e=await this.db.select().from(a);this.cache=e.reduce((t,s)=>(t[s.key]=s.value,t),{});}await this.loadFromGlobals();}catch{console.warn("ConfigService: Could not load settings from database, using environment fallbacks.");}this.loaded=true;}}async ensureSettingsTable(){if(!u)try{if(typeof this.db?.execute=="function"){let{sql:e}=await import('drizzle-orm');await this.db.execute(e`
|
|
2
|
-
CREATE TABLE IF NOT EXISTS "settings" (
|
|
3
|
-
"key" VARCHAR(255) PRIMARY KEY,
|
|
4
|
-
"value" TEXT NOT NULL,
|
|
5
|
-
"description" TEXT,
|
|
6
|
-
"updated_at" TIMESTAMP DEFAULT NOW()
|
|
7
|
-
)
|
|
8
|
-
`),u=!0;}else typeof this.db?.exec=="function"&&(this.db.exec(`
|
|
9
|
-
CREATE TABLE IF NOT EXISTS settings (
|
|
10
|
-
key TEXT PRIMARY KEY,
|
|
11
|
-
value TEXT NOT NULL,
|
|
12
|
-
description TEXT,
|
|
13
|
-
updated_at TEXT
|
|
14
|
-
)
|
|
15
|
-
`),u=!0);}catch{}}async loadFromGlobals(){try{let e=null;if(typeof this.db?.findOne=="function")try{let r=await this.db.findOne({collection:"_globals_storage-settings",where:{},draft:!0});r&&(e=r);}catch{}if(!e&&typeof this.db?.execute=="function"){let{sql:r}=await import('drizzle-orm'),i=['"_globals_storage-settings"','"_globals_storage_settings"','"global_storage_settings"'];for(let a of i)try{let o=await this.db.execute(r`SELECT * FROM ${r.raw(a)} LIMIT 1`);if(e=Array.isArray(o)?o[0]:o?.rows?o.rows[0]:null,e)break}catch{}}else if(!e&&typeof this.db?.prepare=="function"){let r=['"_globals_storage-settings"','"_globals_storage_settings"','"global_storage_settings"'];for(let i of r)try{if(e=this.db.prepare(`SELECT * FROM ${i} LIMIT 1`).get(),e)break}catch{}}if(!e)return;let t=r=>{if(!r)return null;if(typeof r=="string")try{return JSON.parse(r)}catch{return null}return r},s=e.provider||"local";if(this.cache["storage.type"]=s,s==="local"){let r=t(e.local);this.cache["storage.local.dir"]=r?.uploadDir||"./public/uploads",this.cache["storage.local.url"]=r?.baseUrl||"/uploads";}if(s==="aws"){let r=t(e.aws);this.cache["storage.s3.bucket"]=r?.bucket||"",this.cache["storage.s3.region"]=r?.region||"us-east-1",this.cache["storage.s3.access_key_id"]=r?.accessKeyId||"",this.cache["storage.s3.secret_access_key"]=r?.secretAccessKey||"",this.cache["storage.s3.endpoint"]=r?.endpoint||"",this.cache["storage.s3.cdn_url"]=r?.cdnUrl||"",this.cache["storage.s3.prefix"]=r?.prefix||"";}if(s==="r2"){let r=t(e.r2);this.cache["storage.r2.account_id"]=r?.accountId||"",this.cache["storage.r2.access_key_id"]=r?.accessKeyId||"",this.cache["storage.r2.secret_access_key"]=r?.secretAccessKey||"",this.cache["storage.r2.bucket"]=r?.bucket||"",this.cache["storage.r2.cdn_url"]=r?.cdnUrl||"",this.cache["storage.r2.prefix"]=r?.prefix||"";}if(s==="cloudinary"){let r=t(e.cloudinary);this.cache["storage.cloudinary.cloud_name"]=r?.cloudName||"",this.cache["storage.cloudinary.api_key"]=r?.apiKey||"",this.cache["storage.cloudinary.api_secret"]=r?.apiSecret||"",this.cache["storage.cloudinary.folder"]=r?.folder||"";}if(s==="ftp"){let r=t(e.ftp);this.cache["storage.ftp.host"]=r?.host||"",this.cache["storage.ftp.port"]=String(r?.port||"21"),this.cache["storage.ftp.user"]=r?.user||"",this.cache["storage.ftp.password"]=r?.password||"",this.cache["storage.ftp.secure"]=r?.secure?"true":"false",this.cache["storage.ftp.base_url"]=r?.baseUrl||"",this.cache["storage.ftp.prefix"]=r?.prefix||"";}}catch(e){console.warn("ConfigService: Could not load storage settings from globals table:",e);}try{let e=null;if(typeof this.db?.findOne=="function")try{let t=await this.db.findOne({collection:"_globals_email-settings",where:{},draft:!0});t&&(e=t);}catch{}if(!e&&typeof this.db?.execute=="function"){let{sql:t}=await import('drizzle-orm'),s=['"_globals_email-settings"','"_globals_email_settings"','"global_email_settings"'];for(let r of s)try{let i=await this.db.execute(t`SELECT * FROM ${t.raw(r)} LIMIT 1`);if(e=Array.isArray(i)?i[0]:i?.rows?i.rows[0]:null,e)break}catch{}}else if(!e&&typeof this.db?.prepare=="function"){let t=['"_globals_email-settings"','"_globals_email_settings"','"global_email_settings"'];for(let s of t)try{if(e=this.db.prepare(`SELECT * FROM ${s} LIMIT 1`).get(),e)break}catch{}}if(e){let t=s=>{if(!s)return null;if(typeof s=="string")try{return JSON.parse(s)}catch{return null}return s};if(this.cache["email.provider"]=e.provider||"smtp",this.cache["email.smtp.from"]=e.fromEmail||"",this.cache["email.smtp.from_name"]=e.fromName||"",this.cache["email.smtp.reply_to"]=e.replyTo||"",e.provider==="smtp"){let s=t(e.smtp);this.cache["email.smtp.host"]=s?.host||"",this.cache["email.smtp.port"]=String(s?.port||"587"),this.cache["email.smtp.user"]=s?.username||"",this.cache["email.smtp.pass"]=s?.password||"",this.cache["email.smtp.secure"]=s?.secure?"true":"false";}else if(e.provider==="resend"){let s=t(e.resend);this.cache["email.smtp.pass"]=s?.apiKey||"";}else if(e.provider==="sendgrid"){let s=t(e.sendgrid);this.cache["email.smtp.pass"]=s?.apiKey||"";}else if(e.provider==="mailgun"){let s=t(e.mailgun);this.cache["email.smtp.pass"]=s?.apiKey||"";}else if(e.provider==="ses"){let s=t(e.ses);this.cache["email.smtp.user"]=s?.accessKeyId||"",this.cache["email.smtp.pass"]=s?.secretAccessKey||"";}}}catch(e){console.warn("ConfigService: Could not load email settings from globals table:",e);}}get(e,t,s){return this.cache[e]?this.cache[e]:t&&process.env[t]?process.env[t]:s}getStorageConfig(){return {type:this.get("storage.type","STORAGE_TYPE","local"),s3:{bucket:this.get("storage.s3.bucket","STORAGE_BUCKET"),region:this.get("storage.s3.region","STORAGE_REGION","us-east-1"),accessKeyId:this.get("storage.s3.access_key_id","STORAGE_ACCESS_KEY_ID"),secretAccessKey:this.get("storage.s3.secret_access_key","STORAGE_SECRET_ACCESS_KEY"),endpoint:this.get("storage.s3.endpoint","STORAGE_ENDPOINT"),cdnUrl:this.get("storage.s3.cdn_url","STORAGE_CDN_URL"),prefix:this.get("storage.s3.prefix","STORAGE_PREFIX")},r2:{accountId:this.get("storage.r2.account_id","R2_ACCOUNT_ID"),accessKeyId:this.get("storage.r2.access_key_id","R2_ACCESS_KEY_ID"),secretAccessKey:this.get("storage.r2.secret_access_key","R2_SECRET_ACCESS_KEY"),bucket:this.get("storage.r2.bucket","R2_BUCKET"),cdnUrl:this.get("storage.r2.cdn_url","R2_CDN_URL"),prefix:this.get("storage.r2.prefix","R2_PREFIX")},gcs:{bucket:this.get("storage.gcs.bucket","GCS_BUCKET"),projectId:this.get("storage.gcs.project_id","GCS_PROJECT_ID"),clientEmail:this.get("storage.gcs.client_email","GCS_CLIENT_EMAIL"),privateKey:this.get("storage.gcs.private_key","GCS_PRIVATE_KEY"),cdnUrl:this.get("storage.gcs.cdn_url","GCS_CDN_URL"),prefix:this.get("storage.gcs.prefix","GCS_PREFIX")},digitalocean:{bucket:this.get("storage.digitalocean.bucket","DO_BUCKET"),region:this.get("storage.digitalocean.region","DO_REGION","nyc3"),accessKeyId:this.get("storage.digitalocean.access_key_id","DO_ACCESS_KEY_ID"),secretAccessKey:this.get("storage.digitalocean.secret_access_key","DO_SECRET_ACCESS_KEY"),cdnUrl:this.get("storage.digitalocean.cdn_url","DO_CDN_URL"),prefix:this.get("storage.digitalocean.prefix","DO_PREFIX")},backblaze:{bucket:this.get("storage.backblaze.bucket","BB_BUCKET"),accountId:this.get("storage.backblaze.account_id","BB_ACCOUNT_ID"),applicationKeyId:this.get("storage.backblaze.application_key_id","BB_APPLICATION_KEY_ID"),applicationKey:this.get("storage.backblaze.application_key","BB_APPLICATION_KEY"),cdnUrl:this.get("storage.backblaze.cdn_url","BB_CDN_URL"),prefix:this.get("storage.backblaze.prefix","BB_PREFIX")},wasabi:{bucket:this.get("storage.wasabi.bucket","WASABI_BUCKET"),region:this.get("storage.wasabi.region","WASABI_REGION","us-east-1"),accessKeyId:this.get("storage.wasabi.access_key_id","WASABI_ACCESS_KEY_ID"),secretAccessKey:this.get("storage.wasabi.secret_access_key","WASABI_SECRET_ACCESS_KEY"),cdnUrl:this.get("storage.wasabi.cdn_url","WASABI_CDN_URL"),prefix:this.get("storage.wasabi.prefix","WASABI_PREFIX")},bunny:{storageZone:this.get("storage.bunny.storage_zone","BUNNY_STORAGE_ZONE"),apiKey:this.get("storage.bunny.api_key","BUNNY_API_KEY"),cdnUrl:this.get("storage.bunny.cdn_url","BUNNY_CDN_URL"),prefix:this.get("storage.bunny.prefix","BUNNY_PREFIX")},ftp:{host:this.get("storage.ftp.host","FTP_HOST"),port:parseInt(this.get("storage.ftp.port","FTP_PORT","21"),10),user:this.get("storage.ftp.user","FTP_USER"),password:this.get("storage.ftp.password","FTP_PASSWORD"),secure:this.get("storage.ftp.secure","FTP_SECURE")==="true",baseUrl:this.get("storage.ftp.base_url","FTP_BASE_URL"),prefix:this.get("storage.ftp.prefix","FTP_PREFIX")},cloudinary:{cloudName:this.get("storage.cloudinary.cloud_name","CLOUDINARY_CLOUD_NAME"),apiKey:this.get("storage.cloudinary.api_key","CLOUDINARY_API_KEY"),apiSecret:this.get("storage.cloudinary.api_secret","CLOUDINARY_API_SECRET"),folder:this.get("storage.cloudinary.folder","CLOUDINARY_FOLDER")},imgix:{domain:this.get("storage.imgix.domain","IMGIX_DOMAIN"),signKey:this.get("storage.imgix.sign_key","IMGIX_SIGN_KEY")},local:{uploadDir:this.get("storage.local.dir","STORAGE_LOCAL_DIR","./public/uploads"),baseUrl:this.get("storage.local.url","STORAGE_LOCAL_URL","/uploads")}}}getEmailConfig(){return {provider:this.get("email.provider","EMAIL_PROVIDER","smtp"),host:this.get("email.smtp.host","SMTP_HOST"),port:parseInt(this.get("email.smtp.port","SMTP_PORT","587"),10),secure:this.get("email.smtp.secure","SMTP_SECURE")==="true",user:this.get("email.smtp.user","SMTP_USER"),pass:this.get("email.smtp.pass","SMTP_PASS"),from:this.get("email.smtp.from","SMTP_FROM","noreply@example.com"),fromName:this.get("email.smtp.from_name","SMTP_FROM_NAME","Kyro CMS"),replyTo:this.get("email.smtp.reply_to","SMTP_REPLY_TO")}}maskSensitive(e,t){return t&&(n.SENSITIVE_KEYS.includes(e)?"********":t)}async set(e,t,s){await this.db.insert(a).values({key:e,value:t,description:s,updatedAt:new Date}).onConflictDoUpdate({target:[a.key],set:{value:t,description:s,updatedAt:new Date}}),this.cache[e]=t;}};var b={verifyEmail:(n,e="User")=>({subject:"Verify your email address",html:`
|
|
16
|
-
<!DOCTYPE html>
|
|
17
|
-
<html>
|
|
18
|
-
<head>
|
|
19
|
-
<meta charset="utf-8">
|
|
20
|
-
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
21
|
-
<title>Verify Email</title>
|
|
22
|
-
<style>
|
|
23
|
-
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; line-height: 1.6; color: #333; }
|
|
24
|
-
.container { max-width: 600px; margin: 0 auto; padding: 20px; }
|
|
25
|
-
.button { display: inline-block; padding: 12px 24px; background: #0b1222; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; }
|
|
26
|
-
.footer { margin-top: 30px; font-size: 12px; color: #666; }
|
|
27
|
-
</style>
|
|
28
|
-
</head>
|
|
29
|
-
<body>
|
|
30
|
-
<div class="container">
|
|
31
|
-
<h1>Welcome, ${e}!</h1>
|
|
32
|
-
<p>Please verify your email address by clicking the button below:</p>
|
|
33
|
-
<p style="text-align: center; margin: 30px 0;">
|
|
34
|
-
<a href="${n}" class="button">Verify Email</a>
|
|
35
|
-
</p>
|
|
36
|
-
<p>Or copy and paste this link into your browser:</p>
|
|
37
|
-
<p style="word-break: break-all; color: #666;">${n}</p>
|
|
38
|
-
<p>This link will expire in 24 hours.</p>
|
|
39
|
-
<div class="footer">
|
|
40
|
-
<p>If you didn't create an account, you can safely ignore this email.</p>
|
|
41
|
-
</div>
|
|
42
|
-
</div>
|
|
43
|
-
</body>
|
|
44
|
-
</html>
|
|
45
|
-
`,text:`Welcome ${e}!
|
|
46
|
-
|
|
47
|
-
Please verify your email by clicking this link: ${n}
|
|
48
|
-
|
|
49
|
-
This link will expire in 24 hours.
|
|
50
|
-
|
|
51
|
-
If you didn't create an account, you can safely ignore this email.`}),resetPassword:(n,e="User")=>({subject:"Reset your password",html:`
|
|
52
|
-
<!DOCTYPE html>
|
|
53
|
-
<html>
|
|
54
|
-
<head>
|
|
55
|
-
<meta charset="utf-8">
|
|
56
|
-
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
57
|
-
<title>Reset Password</title>
|
|
58
|
-
<style>
|
|
59
|
-
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; line-height: 1.6; color: #333; }
|
|
60
|
-
.container { max-width: 600px; margin: 0 auto; padding: 20px; }
|
|
61
|
-
.button { display: inline-block; padding: 12px 24px; background: #dc2626; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; }
|
|
62
|
-
.warning { background: #fef3c7; border: 1px solid #f59e0b; padding: 12px; border-radius: 6px; margin: 20px 0; }
|
|
63
|
-
.footer { margin-top: 30px; font-size: 12px; color: #666; }
|
|
64
|
-
</style>
|
|
65
|
-
</head>
|
|
66
|
-
<body>
|
|
67
|
-
<div class="container">
|
|
68
|
-
<h1>Password Reset Request</h1>
|
|
69
|
-
<p>Hello ${e},</p>
|
|
70
|
-
<p>We received a request to reset your password. Click the button below to create a new password:</p>
|
|
71
|
-
<p style="text-align: center; margin: 30px 0;">
|
|
72
|
-
<a href="${n}" class="button">Reset Password</a>
|
|
73
|
-
</p>
|
|
74
|
-
<p>Or copy and paste this link into your browser:</p>
|
|
75
|
-
<p style="word-break: break-all; color: #666;">${n}</p>
|
|
76
|
-
<div class="warning">
|
|
77
|
-
<strong>\u26A0\uFE0F Important:</strong> This link will expire in 1 hour. If you didn't request a password reset, please ignore this email or contact support if you have concerns.
|
|
78
|
-
</div>
|
|
79
|
-
<div class="footer">
|
|
80
|
-
<p>For security reasons, please don't share this email with anyone.</p>
|
|
81
|
-
</div>
|
|
82
|
-
</div>
|
|
83
|
-
</body>
|
|
84
|
-
</html>
|
|
85
|
-
`,text:`Password Reset Request
|
|
86
|
-
|
|
87
|
-
Hello ${e},
|
|
88
|
-
|
|
89
|
-
We received a request to reset your password. Click this link to create a new password: ${n}
|
|
90
|
-
|
|
91
|
-
This link will expire in 1 hour.
|
|
92
|
-
|
|
93
|
-
If you didn't request a password reset, please ignore this email.`}),welcome:(n="User")=>({subject:"Welcome to Kyro CMS",html:`
|
|
94
|
-
<!DOCTYPE html>
|
|
95
|
-
<html>
|
|
96
|
-
<head>
|
|
97
|
-
<meta charset="utf-8">
|
|
98
|
-
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
99
|
-
<title>Welcome</title>
|
|
100
|
-
<style>
|
|
101
|
-
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; line-height: 1.6; color: #333; }
|
|
102
|
-
.container { max-width: 600px; margin: 0 auto; padding: 20px; }
|
|
103
|
-
.button { display: inline-block; padding: 12px 24px; background: #0b1222; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; }
|
|
104
|
-
</style>
|
|
105
|
-
</head>
|
|
106
|
-
<body>
|
|
107
|
-
<div class="container">
|
|
108
|
-
<h1>Welcome to Kyro CMS, ${n}!</h1>
|
|
109
|
-
<p>Your account has been created successfully.</p>
|
|
110
|
-
<p>You can now:</p>
|
|
111
|
-
<ul>
|
|
112
|
-
<li>Manage your content collections</li>
|
|
113
|
-
<li>Upload and organize media</li>
|
|
114
|
-
<li>Configure settings</li>
|
|
115
|
-
<li>And much more...</li>
|
|
116
|
-
</ul>
|
|
117
|
-
<p style="text-align: center; margin: 30px 0;">
|
|
118
|
-
<a href="#" class="button">Get Started</a>
|
|
119
|
-
</p>
|
|
120
|
-
<p>If you have any questions, feel free to reach out to our support team.</p>
|
|
121
|
-
</div>
|
|
122
|
-
</body>
|
|
123
|
-
</html>
|
|
124
|
-
`,text:`Welcome to Kyro CMS, ${n}!
|
|
125
|
-
|
|
126
|
-
Your account has been created successfully.
|
|
127
|
-
|
|
128
|
-
You can now:
|
|
129
|
-
- Manage your content collections
|
|
130
|
-
- Upload and organize media
|
|
131
|
-
- Configure settings
|
|
132
|
-
- And much more...
|
|
133
|
-
|
|
134
|
-
Get started by logging into your dashboard.`}),accountLocked:(n,e,t="User")=>({subject:"Account Security Alert - Account Locked",html:`
|
|
135
|
-
<!DOCTYPE html>
|
|
136
|
-
<html>
|
|
137
|
-
<head>
|
|
138
|
-
<meta charset="utf-8">
|
|
139
|
-
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
140
|
-
<title>Account Locked</title>
|
|
141
|
-
<style>
|
|
142
|
-
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; line-height: 1.6; color: #333; }
|
|
143
|
-
.container { max-width: 600px; margin: 0 auto; padding: 20px; }
|
|
144
|
-
.alert { background: #fef2f2; border: 1px solid #ef4444; padding: 16px; border-radius: 8px; margin: 20px 0; }
|
|
145
|
-
.footer { margin-top: 30px; font-size: 12px; color: #666; }
|
|
146
|
-
</style>
|
|
147
|
-
</head>
|
|
148
|
-
<body>
|
|
149
|
-
<div class="container">
|
|
150
|
-
<h1>Account Security Alert</h1>
|
|
151
|
-
<p>Hello ${t},</p>
|
|
152
|
-
<div class="alert">
|
|
153
|
-
<p><strong>\u26A0\uFE0F Your account has been temporarily locked due to multiple failed login attempts.</strong></p>
|
|
154
|
-
<p>Failed attempts: ${n}</p>
|
|
155
|
-
<p>Lockout duration: ${Math.round(e/6e4)} minutes</p>
|
|
156
|
-
</div>
|
|
157
|
-
<p>Your account will automatically unlock after the lockout period expires.</p>
|
|
158
|
-
<p>If this wasn't you, we recommend:</p>
|
|
159
|
-
<ul>
|
|
160
|
-
<li>Using a strong, unique password</li>
|
|
161
|
-
<li>Enabling two-factor authentication (coming soon)</li>
|
|
162
|
-
<li>Reviewing your recent account activity</li>
|
|
163
|
-
</ul>
|
|
164
|
-
<div class="footer">
|
|
165
|
-
<p>If you need immediate assistance, please contact support.</p>
|
|
166
|
-
</div>
|
|
167
|
-
</div>
|
|
168
|
-
</body>
|
|
169
|
-
</html>
|
|
170
|
-
`,text:`Account Security Alert
|
|
171
|
-
|
|
172
|
-
Hello ${t},
|
|
173
|
-
|
|
174
|
-
Your account has been temporarily locked due to multiple failed login attempts (${n}).
|
|
175
|
-
|
|
176
|
-
Lockout duration: ${Math.round(e/6e4)} minutes
|
|
177
|
-
|
|
178
|
-
Your account will automatically unlock after this period.
|
|
179
|
-
|
|
180
|
-
If this wasn't you, we recommend using a strong, unique password.`}),passwordChanged:(n="User")=>({subject:"Your password has been changed",html:`
|
|
181
|
-
<!DOCTYPE html>
|
|
182
|
-
<html>
|
|
183
|
-
<head>
|
|
184
|
-
<meta charset="utf-8">
|
|
185
|
-
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
186
|
-
<title>Password Changed</title>
|
|
187
|
-
<style>
|
|
188
|
-
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; line-height: 1.6; color: #333; }
|
|
189
|
-
.container { max-width: 600px; margin: 0 auto; padding: 20px; }
|
|
190
|
-
.info { background: #f0fdf4; border: 1px solid #22c55e; padding: 12px; border-radius: 6px; margin: 20px 0; }
|
|
191
|
-
</style>
|
|
192
|
-
</head>
|
|
193
|
-
<body>
|
|
194
|
-
<div class="container">
|
|
195
|
-
<h1>Password Changed</h1>
|
|
196
|
-
<p>Hello ${n},</p>
|
|
197
|
-
<div class="info">
|
|
198
|
-
<p>Your password was recently changed.</p>
|
|
199
|
-
</div>
|
|
200
|
-
<p>If you did this, you can safely ignore this email.</p>
|
|
201
|
-
<p><strong>If you didn't change your password</strong>, please contact our support team immediately as your account may have been compromised.</p>
|
|
202
|
-
</div>
|
|
203
|
-
</body>
|
|
204
|
-
</html>
|
|
205
|
-
`,text:`Password Changed
|
|
206
|
-
|
|
207
|
-
Hello ${n},
|
|
208
|
-
|
|
209
|
-
Your password was recently changed.
|
|
210
|
-
|
|
211
|
-
If you did this, you can safely ignore this email.
|
|
212
|
-
|
|
213
|
-
If you didn't change your password, please contact support immediately.`}),newLogin:(n,e,t="User")=>({subject:"New login to your account",html:`
|
|
214
|
-
<!DOCTYPE html>
|
|
215
|
-
<html>
|
|
216
|
-
<head>
|
|
217
|
-
<meta charset="utf-8">
|
|
218
|
-
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
219
|
-
<title>New Login</title>
|
|
220
|
-
<style>
|
|
221
|
-
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; line-height: 1.6; color: #333; }
|
|
222
|
-
.container { max-width: 600px; margin: 0 auto; padding: 20px; }
|
|
223
|
-
.info-box { background: #f8fafc; border: 1px solid #e2e8f0; padding: 16px; border-radius: 8px; margin: 20px 0; }
|
|
224
|
-
.footer { margin-top: 30px; font-size: 12px; color: #666; }
|
|
225
|
-
</style>
|
|
226
|
-
</head>
|
|
227
|
-
<body>
|
|
228
|
-
<div class="container">
|
|
229
|
-
<h1>New Login Detected</h1>
|
|
230
|
-
<p>Hello ${t},</p>
|
|
231
|
-
<p>We detected a new login to your account:</p>
|
|
232
|
-
<div class="info-box">
|
|
233
|
-
<p><strong>Location:</strong> ${n}</p>
|
|
234
|
-
<p><strong>Time:</strong> ${e}</p>
|
|
235
|
-
</div>
|
|
236
|
-
<p><strong>If this was you</strong>, no action is needed.</p>
|
|
237
|
-
<p><strong>If this wasn't you</strong>, your account may be compromised. Please:</p>
|
|
238
|
-
<ol>
|
|
239
|
-
<li>Change your password immediately</li>
|
|
240
|
-
<li>Review your recent account activity</li>
|
|
241
|
-
<li>Contact support if needed</li>
|
|
242
|
-
</ol>
|
|
243
|
-
<div class="footer">
|
|
244
|
-
<p>This is an automated security notification.</p>
|
|
245
|
-
</div>
|
|
246
|
-
</div>
|
|
247
|
-
</body>
|
|
248
|
-
</html>
|
|
249
|
-
`,text:`New Login Detected
|
|
250
|
-
|
|
251
|
-
Hello ${t},
|
|
252
|
-
|
|
253
|
-
We detected a new login to your account:
|
|
254
|
-
|
|
255
|
-
Location: ${n}
|
|
256
|
-
Time: ${e}
|
|
257
|
-
|
|
258
|
-
If this wasn't you, please change your password immediately and contact support.`})},h=class n{transporter;config;templates;transporterInitialized=false;constructor(e,t){this.config=e,this.templates={...b,...t};}async ensureTransporter(){if(this.transporterInitialized)return this.transporter;let{default:e}=await import('nodemailer');return this.config.provider==="smtp"&&this.config.smtp?this.transporter=e.createTransport({host:this.config.smtp.host,port:this.config.smtp.port,secure:this.config.smtp.secure,auth:this.config.smtp.auth}):this.config.provider==="ses"&&this.config.ses&&(this.transporter=e.createTransport({host:`email-smtp.${this.config.ses.region}.amazonaws.com`,port:587,secure:false,auth:{user:this.config.ses.accessKeyId,pass:this.config.ses.secretAccessKey}})),this.transporterInitialized=true,this.transporter}async send(e){let{provider:t,from:s,fromName:r,replyTo:i}=this.config,a=`"${r||"Kyro CMS"}" <${s}>`,o=e.replyTo||i;try{let c;switch(t){case "smtp":case "ses":{let l=await this.ensureTransporter();if(!l)throw new Error(`${t} transporter not initialized`);c=await l.sendMail({from:a,to:Array.isArray(e.to)?e.to.join(", "):e.to,subject:e.subject,html:e.html,text:e.text,replyTo:o});}break;case "resend":c=await this.sendViaResend(a,e,o);break;case "sendgrid":c=await this.sendViaSendGrid(a,e,o);break;case "mailgun":c=await this.sendViaMailgun(a,e,o);break;default:throw new Error(`Unsupported email provider: ${t}`)}return c}catch(c){throw console.error("[EmailTransport] FAILED to send email:",c.message),c.response&&console.error("[EmailTransport] Provider Error Detail:",JSON.stringify(c.response,null,2)),c}}async sendViaResend(e,t,s){let r=this.config.resend?.apiKey;if(!r)throw new Error("Resend API Key missing");let i={from:e,to:t.to,subject:t.subject,html:t.html,text:t.text,reply_to:s},a=await fetch("https://api.resend.com/emails",{method:"POST",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"},body:JSON.stringify(i)});if(!a.ok){let o=await a.json();throw new Error(`Resend Error: ${JSON.stringify(o)}`)}return a.json()}async sendViaSendGrid(e,t,s){let r=this.config.sendgrid?.apiKey;if(!r)throw new Error("SendGrid API Key missing");let i={personalizations:[{to:Array.isArray(t.to)?t.to.map(o=>({email:o})):[{email:t.to}]}],from:{email:e.match(/<(.+)>/)?.[1]||e,name:e.match(/"(.+)"/)?.[1]},subject:t.subject,content:[{type:"text/plain",value:t.text||""},{type:"text/html",value:t.html}],reply_to:s?{email:s}:void 0},a=await fetch("https://api.sendgrid.com/v3/mail/send",{method:"POST",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"},body:JSON.stringify(i)});if(!a.ok){let o=await a.json();throw new Error(`SendGrid Error: ${JSON.stringify(o)}`)}return {success:true}}async sendViaMailgun(e,t,s){let{apiKey:r,domain:i,region:a}=this.config.mailgun||{};if(!r||!i)throw new Error("Mailgun config missing");let o=a==="eu"?"api.eu.mailgun.net":"api.mailgun.net",c=btoa(`api:${r}`),l=new URLSearchParams;l.append("from",e);let f=Array.isArray(t.to)?t.to.join(", "):t.to;l.append("to",f),l.append("subject",t.subject),l.append("html",t.html),t.text&&l.append("text",t.text),s&&l.append("h:Reply-To",s);let d=await fetch(`https://${o}/v3/${i}/messages`,{method:"POST",headers:{Authorization:`Basic ${c}`,"Content-Type":"application/x-www-form-urlencoded"},body:l});if(!d.ok){let y=await d.json();throw new Error(`Mailgun Error: ${JSON.stringify(y)}`)}return d.json()}getTemplates(){return this.templates}async verifyConnection(){if(this.config.provider==="smtp"||this.config.provider==="ses")try{let e=await this.ensureTransporter();if(e)return await e.verify(),!0}catch{return false}return !!(this.config.resend?.apiKey||this.config.sendgrid?.apiKey||this.config.mailgun?.apiKey)}static async fromConfig(e){let t=new p(e);await t.load();let s=t.getEmailConfig();if(!s.provider)return this.fromEnv();let r={provider:s.provider||"smtp",from:s.from||"noreply@example.com",fromName:s.fromName,replyTo:s.replyTo,smtp:s.provider==="smtp"?{host:s.host||"",port:s.port||587,secure:s.secure||false,auth:{user:s.user||"",pass:s.pass||""}}:void 0,resend:s.provider==="resend"?{apiKey:s.pass||""}:void 0,sendgrid:s.provider==="sendgrid"?{apiKey:s.pass||""}:void 0,mailgun:s.provider==="mailgun"?{apiKey:s.pass||"",domain:s.host||"",region:s.secure?"eu":"us"}:void 0,ses:s.provider==="ses"?{accessKeyId:s.user||"",secretAccessKey:s.pass||"",region:s.host||"us-east-1"}:void 0};return new n(r)}static fromEnv(){let e=process.env.EMAIL_PROVIDER||"smtp",t=process.env.SMTP_FROM||process.env.DEFAULT_FROM||"noreply@example.com",s=process.env.SMTP_FROM_NAME||"Kyro CMS",r=process.env.SMTP_REPLY_TO;if(e==="smtp"){let i=process.env.SMTP_HOST,a=process.env.SMTP_USER,o=process.env.SMTP_PASS;return !i||!a||!o?null:new n({provider:"smtp",from:t,fromName:s,replyTo:r,smtp:{host:i,port:parseInt(process.env.SMTP_PORT||"587",10),secure:process.env.SMTP_SECURE==="true",auth:{user:a,pass:o}}})}if(e==="resend"){let i=process.env.RESEND_API_KEY||process.env.SMTP_PASS;return i?new n({provider:"resend",from:t,fromName:s,replyTo:r,resend:{apiKey:i}}):null}if(e==="sendgrid"){let i=process.env.SENDGRID_API_KEY||process.env.SMTP_PASS;return i?new n({provider:"sendgrid",from:t,fromName:s,replyTo:r,sendgrid:{apiKey:i}}):null}if(e==="mailgun"){let i=process.env.MAILGUN_API_KEY||process.env.SMTP_PASS,a=process.env.MAILGUN_DOMAIN||process.env.SMTP_HOST;return !i||!a?null:new n({provider:"mailgun",from:t,fromName:s,replyTo:r,mailgun:{apiKey:i,domain:a,region:process.env.MAILGUN_REGION||(process.env.SMTP_SECURE==="true"?"eu":"us")}})}if(e==="ses"){let i=process.env.AWS_ACCESS_KEY_ID||process.env.SMTP_USER,a=process.env.AWS_SECRET_ACCESS_KEY||process.env.SMTP_PASS,o=process.env.AWS_REGION||process.env.SMTP_HOST||"us-east-1";return !i||!a?null:new n({provider:"ses",from:t,fromName:s,replyTo:r,ses:{accessKeyId:i,secretAccessKey:a,region:o}})}return null}};var _={minLength:12,requireUppercase:true,requireLowercase:true,requireNumbers:true,requireSpecialChars:true,preventReuse:5,maxLength:128},m=class{config;constructor(e={}){this.config={..._,...e};}validate(e){let t=[];return this.config.maxLength&&e.length>this.config.maxLength&&t.push(`Password must not exceed ${this.config.maxLength} characters`),e.length<this.config.minLength&&t.push(`Password must be at least ${this.config.minLength} characters`),this.config.requireUppercase&&!/[A-Z]/.test(e)&&t.push("Password must contain at least one uppercase letter"),this.config.requireLowercase&&!/[a-z]/.test(e)&&t.push("Password must contain at least one lowercase letter"),this.config.requireNumbers&&!/[0-9]/.test(e)&&t.push("Password must contain at least one number"),this.config.requireSpecialChars&&!/[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(e)&&t.push("Password must contain at least one special character"),["password","123456","12345678","qwerty","abc123","monkey","1234567","letmein","trustno1","dragon","baseball","iloveyou","master","sunshine","ashley","football","password1","shadow","123123","654321"].includes(e.toLowerCase())&&t.push("This password is too common. Please choose a more secure password"),(/^[a-zA-Z]+$/.test(e)||/^[0-9]+$/.test(e))&&t.push("Password must contain a mix of letters, numbers, and/or special characters"),/(.)\1{2,}/.test(e)&&t.push("Password must not contain more than 2 consecutive identical characters"),/^(012|123|234|345|456|567|678|789|890|098|987|876|765|654|543|432|321|210)+$/i.test(e)&&t.push("Password must not contain sequential numbers or letters"),{valid:t.length===0,errors:t}}async checkReuse(e,t,s){return {valid:true,errors:[]}}async isInHistory(e,t,s){for(let r of t)if(await s(e,r))return true;return false}generatePassword(e=16){let t="ABCDEFGHIJKLMNOPQRSTUVWXYZ",s="abcdefghijklmnopqrstuvwxyz",r="0123456789",i="!@#$%^&*()_+-=[]{}|;:,.<>?",a="";a+=t[Math.floor(Math.random()*t.length)],a+=s[Math.floor(Math.random()*s.length)],a+=r[Math.floor(Math.random()*r.length)],a+=i[Math.floor(Math.random()*i.length)];let o=t+s+r+i;for(let c=a.length;c<e;c++)a+=o[Math.floor(Math.random()*o.length)];return a.split("").sort(()=>Math.random()-.5).join("")}getStrength(e){let t=0,s=[];e.length>=8&&(t+=1),e.length>=12&&(t+=1),e.length>=16&&(t+=1),/[a-z]/.test(e)&&(t+=1),/[A-Z]/.test(e)&&(t+=1),/[0-9]/.test(e)&&(t+=1),/[!@#$%^&*()_+\-=\[\]{}|;:,.<>?]/.test(e)&&(t+=1),e.length>8&&(t+=1),e.length>12&&(t+=1);let r=new Set(e).size;r>6&&(t+=1),r>10&&(t+=1);let i;return t<=3?(i="Weak",s.push("Add more characters"),s.push("Include uppercase and lowercase letters")):t<=5?(i="Fair",s.push("Add special characters"),s.push("Consider making it longer")):t<=7?(i="Good",s.push("Consider making it longer for extra security")):i="Strong",{score:t,label:i,feedback:s}}setConfig(e){this.config={...this.config,...e};}getConfig(){return {...this.config}}};
|
|
259
|
-
export{p as a,h as b,m as c};
|