@kyro-cms/core 0.12.67 → 0.12.68
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/{chunk-2XUD2OPJ.js → chunk-2ZACCXDM.js} +1 -1
- package/dist/{chunk-CTIQQ3ZX.cjs → chunk-IPTUGJED.cjs} +3 -3
- package/dist/{chunk-ZED7JS6I.cjs → chunk-OTSDT3NH.cjs} +1 -1
- package/dist/{chunk-HEGM2QMX.js → chunk-QVE74KG7.js} +1 -1
- package/dist/{chunk-EJN3FJWB.js → chunk-S5M2GT3D.js} +1 -1
- package/dist/{chunk-GH4OVDIL.cjs → chunk-XIUW5U64.cjs} +1 -1
- package/dist/index.cjs +3 -3
- package/dist/index.js +1 -1
- package/dist/rest/index.cjs +1 -1
- package/dist/rest/index.js +1 -1
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export{a as LocalAdapter,b as createLocalAdapter}from'./chunk-JCEJ4VTN.js';export{a as RedisAuthAdapter}from'./chunk-M75VGFCI.js';import {a as a$5}from'./chunk-RPRGGGIW.js';export{k as allGlobalSettings,q as blogCollections,l as coreGlobalSettings,V as createTemplateConfig,r as ecommerceCollections,s as ecommerceGlobals,t as kitchenSinkCollections,v as mediaCollections,a as minimalCollections,U as templateCollections}from'./chunk-VTOL3URF.js';export{a as kyro}from'./chunk-XDPLVJRO.js';import {f}from'./chunk-
|
|
1
|
+
export{a as LocalAdapter,b as createLocalAdapter}from'./chunk-JCEJ4VTN.js';export{a as RedisAuthAdapter}from'./chunk-M75VGFCI.js';import {a as a$5}from'./chunk-RPRGGGIW.js';export{k as allGlobalSettings,q as blogCollections,l as coreGlobalSettings,V as createTemplateConfig,r as ecommerceCollections,s as ecommerceGlobals,t as kitchenSinkCollections,v as mediaCollections,a as minimalCollections,U as templateCollections}from'./chunk-VTOL3URF.js';export{a as kyro}from'./chunk-XDPLVJRO.js';import {f}from'./chunk-QVE74KG7.js';export{t as AnalyticsPlugin,u as CommentsPlugin,a as ConfigValidationError,y as Kyro,q as KyroPlugin,B as Logger,r as PluginManager,m as Registry,v as ReviewsPlugin,s as SEOPlugin,w as WishlistPlugin,i as collectionToCreateZod,j as collectionToUpdateZod,k as collectionToWhereZod,h as collectionToZod,z as createKyro,A as createKyroHandler,p as createRegistry,g as fieldToZod,n as getRegistry,l as globalToZod,C as logger,x as presetPlugins,o as resetRegistry,b as validateCollection,e as validateConfig,d as validateFields,c as validateGlobal,f as z}from'./chunk-QVE74KG7.js';export{e as autoBootstrap,a as bootstrapAdmin,f as bootstrapWithRetry,d as getBootstrapFromEnv}from'./chunk-TBTQXIHP.js';import'./chunk-LWM4WABU.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-7FXEXHK6.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-ZRIBWDYJ.js';export{a as FIELD_DEFINITION_KEYS,e as applyBlocksOverrides,g as applyCollectionOverrides,h as applyGlobalOverrides,f as applyTabsOverrides,c as flattenFieldOverrides,b as isFieldOverrideDefinition,d as updateFieldByPath}from'./chunk-JSTDCK3Z.js';import'./chunk-D6SDGHY6.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-4ZWLNGLS.js';export{J as buildGraphQLSchema,K as createGraphQLSchema}from'./chunk-X473JI7Z.js';import {bb,ab,db,eb}from'./chunk-2ZACCXDM.js';export{bb as AuditLogger,db as InMemoryAuditLogger,ab as InMemoryRateLimiter,gb as MediaService,cb as createAuditContext,ib as createKyroApp,_a as createLocalStorage,jb as createRESTAPI,fb as isEdgeRuntime,Za as resolveProvider}from'./chunk-2ZACCXDM.js';import {q,r}from'./chunk-KWGB3YNI.js';export{p as ConfigService,q as EmailTransport,r as PasswordPolicy,o as getEmailTemplates,n as renderAbandonedCart,g as renderAccountLocked,a as renderBaseLayout,f as renderMagicLink,i as renderNewLogin,j as renderOrderConfirmation,l as renderOrderDelivered,m as renderOrderRefunded,k as renderOrderShipped,e as renderPasswordChanged,c as renderResetPassword,h as renderUserInvite,b as renderVerifyEmail,d as renderWelcome}from'./chunk-KWGB3YNI.js';import'./chunk-OLRCZ6E3.js';import {a as a$2}from'./chunk-N6MNQIQU.js';export{a as SQLiteAuthAdapter}from'./chunk-N6MNQIQU.js';import {f as f$1}from'./chunk-6TPICJ2L.js';export{c as getAppSecret,d as getEncryptionKey,e as getSessionConfig,b as loadSecrets,a as setDbAdapter}from'./chunk-6TPICJ2L.js';import'./chunk-YENNL5HG.js';import'./chunk-W45TLOOT.js';import'./chunk-IKGVPXMK.js';import'./chunk-YUUXFD73.js';import'./chunk-LVBHOZZF.js';import'./chunk-OBYAIJVU.js';import'./chunk-JRUQ5ABB.js';import'./chunk-CIVA6SKW.js';import'./chunk-WPM6LFCY.js';import'./chunk-U6KFONKM.js';import'./chunk-TYQYKKWJ.js';import'./chunk-L2QXP26Q.js';export{d as ALL_WEBHOOK_EVENTS,e as WEBHOOK_COLLECTION,f as WEBHOOK_DELIVERY_COLLECTION,c as WEBHOOK_EVENTS,m as WebhookService,k as buildDeliveryRecord,l as createTestPayload,n as createWebhookService,i as deliverWebhook,j as deliverWithRetry,h as generateWebhookSecret,g as signPayload}from'./chunk-AWQGDMOE.js';export{h as evaluateAccess,j as getWhereClause,i as mergeWhereClauses}from'./chunk-GQGFNTDZ.js';export{b as KyroPubSub,c as KyroWSServer,a as PubSub,d as createWSServer}from'./chunk-5M3FKE2V.js';import'./chunk-7MNDQU6K.js';export{c as DrizzleAdapter,b as collectionToDrizzleSchema,d as createDrizzleAdapter,a as fieldToDrizzleType}from'./chunk-MVZSSTCV.js';import'./chunk-JV4HJBXW.js';export{b as createDatabase,c as runMigrations,d as seedDefaultRoles}from'./chunk-4OMQURN7.js';import {a as a$3}from'./chunk-ZWDBPEXL.js';export{a as PostgresAuthAdapter}from'./chunk-ZWDBPEXL.js';import'./chunk-47CXBWMA.js';import'./chunk-EML5FDUU.js';import'./chunk-637PTUHF.js';import'./chunk-N5POANYV.js';import'./chunk-HRAY65XH.js';import'./chunk-2HA6EKXX.js';import'./chunk-FLMUMPDE.js';import'./chunk-3NSZZCOJ.js';export{a as MongoDBAdapter,b as createMongoDBAdapter}from'./chunk-4YCI3HBD.js';import {a as a$1}from'./chunk-5ZEYOFAK.js';export{a as MongoDBAuthAdapter}from'./chunk-5ZEYOFAK.js';import {a as a$4}from'./chunk-SLMIYECU.js';export{a as AbstractBaseAdapter}from'./chunk-SLMIYECU.js';import {a}from'./chunk-P6JITOFF.js';import'./chunk-7NH7H3WA.js';import'./chunk-VVVCCB6R.js';import'./chunk-TBHNE4VV.js';import {g}from'./chunk-Y2YAKDEQ.js';import ee,{randomBytes}from'crypto';import {readFileSync}from'fs';import Xe,{join,resolve}from'path';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
|
|
2
2
|
g();g();g();g();async function He(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 Yr(s,e){return He(s,e)}g();g();var E=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 Fe(s){return new E(s)}g();var O=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(l=>({type:"text",value:String(l)}))}},{type:"close"}]})});if(!o.ok)return [];let i=(await o.json())?.results?.[0]?.response?.result;if(!i||!i.rows)return [];let c=i.cols.map(l=>l.name);return i.rows.map(l=>{let p={};return c.forEach((g,m)=>{p[g]=l[m]?.value??null;}),p})}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 Ke(s){return new O(s)}g();g();g();g();var Jr={maxAttempts:5,lockDuration:9e5,notifyUser:true,notifyAdmin:true,adminNotifyAfter:3},R=class{redis;prefix;config;constructor(e,t={},r="kyro:lockout:"){this.redis=e,this.prefix=r,this.config={...Jr,...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),c=this.redis.pipeline();c.hset(r,{attempts:this.config.maxAttempts.toString(),lockedAt:o.toString(),lockedUntil:i.getTime().toString()}),c.expire(r,Math.ceil(n/1e3)+3600),await c.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,c)=>(c+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};}};g();var Xr={"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}},v=class{redis;prefix;limits;userLimits;constructor(e,t,r,o="kyro:ratelimit:"){this.redis=e,this.prefix=o,this.limits={...Xr,...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,c=this.redis.pipeline();c.zremrangebyscore(o,0,i),c.zcard(o),c.zadd(o,n,`${n}:${Math.random()}`),c.expire(o,Math.ceil(r.window/1e3)+1);let p=(await c.exec())?.[1]?.[1]||0;if(p>=r.max){let g=await this.redis.zrange(o,0,0,"WITHSCORES"),m=g.length>1?parseInt(g[1],10)+r.window:n+r.window;return {allowed:false,remaining:0,resetAt:m,retryAfter:Math.ceil((m-n)/1e3)}}return {allowed:true,remaining:r.max-p-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(),c=i-o.window,l=this.redis.pipeline();l.zremrangebyscore(n,0,c),l.zcard(n),l.zadd(n,i,`${i}:${Math.random()}`),l.expire(n,Math.ceil(o.window/1e3)+1);let g=(await l.exec())?.[1]?.[1]||0;if(g>=o.max){let m=await this.redis.zrange(n,0,0,"WITHSCORES"),f=m.length>1?parseInt(m[1],10)+o.window:i+o.window;return {allowed:false,remaining:0,resetAt:f,retryAfter:Math.ceil((f-i)/1e3)}}return {allowed:true,remaining:o.max-g-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 c=await this.redis.zcard(o);return {count:c,limit:r.max,remaining:Math.max(0,r.max-c),resetAt:n+r.window}}setLimit(e,t){this.limits[e]=t;}setUserLimit(e,t){this.userLimits[e]=t;}};g();g();g();var D=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-ZEEHSMAG.js')).default.hash(e,12)}async verifyPassword(e,t){let r=await this.findUserByEmail(e);return !r||!r.passwordHash?null:await(await import('./bcryptjs-ZEEHSMAG.js')).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,c={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,c),this.refreshTokens.set(n,r),c}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-ZEEHSMAG.js')).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}};g();var I=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 c=o>0?this.config.maxAttempts:0;return {totalFailedAttempts:r,lockoutCount:o,lastLockout:n,averageAttemptsBeforeLockout:c}}shouldNotifyAdmin(e){return this.config.notifyAdmin&&e>=this.config.adminNotifyAfter}getConfig(){return {...this.config}}setConfig(e){this.config={...this.config,...e};}};function b(s,e=""){return process.env[s]||e}function P(s,e=false){let t=process.env[s];return t?t.toLowerCase()==="true":e}function y(s,e=0){let t=process.env[s];return t?parseInt(t,10):e}function Be(){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 to(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:b("KYRO_AUTH_DB_PATH",r)});case "postgres":{let o=b("DATABASE_URL","");if(o){let n,i;try{n=(await import('./postgres-js-WE3NBRFO.js')).drizzle,i=await import('./src-QBADSZV4.js');}catch{a(["postgres","drizzle-orm"]),n=(await import('./postgres-js-WE3NBRFO.js')).drizzle,i=await import('./src-QBADSZV4.js');}let c=i.default(o,{onnotice:()=>{}}),l=n(c);return new a$3({db:l})}return new a$2({path:b("KYRO_AUTH_DB_PATH",r)})}case "mongodb":{let o=b("MONGODB_URI","");if(o){let n;try{let g=await import('./lib-XXYYUPMW.js');n=g.MongoClient??g.default?.MongoClient;}catch{a(["mongodb"]);let m=await import('./lib-XXYYUPMW.js');n=m.MongoClient??m.default?.MongoClient;}let i=new n(o);await i.connect();let l=new URL(o).pathname.replace(/^\//,"")||"kyro_cms",p=i.db(l);return new a$1({db:p})}return new a$2({path:b("KYRO_AUTH_DB_PATH",r)})}default:return new D}}async function G(s,e){let t=P("KYRO_DISTRIBUTED",false),r$1;if(t){let{RedisAuthAdapter:m}=await import('./redis-adapter-QPCTMF55.js'),f=b("REDIS_URL","redis://localhost:6379"),w=P("REDIS_TLS",false),h=new m({url:f,tls:w});await h.connect?.(),r$1=h;}else {let m=s||Be();r$1=await to(m),r$1.connect&&await r$1.connect();}let o=e?await q.fromConfig(e).catch(()=>null)||q.fromEnv()||void 0:q.fromEnv()||void 0,n=new r({minLength:y("PASSWORD_MIN_LENGTH",12),requireUppercase:P("PASSWORD_REQUIRE_UPPERCASE",true),requireLowercase:P("PASSWORD_REQUIRE_LOWERCASE",true),requireNumbers:P("PASSWORD_REQUIRE_NUMBERS",true),requireSpecialChars:P("PASSWORD_REQUIRE_SPECIAL",true),preventReuse:y("PASSWORD_PREVENT_REUSE",5),maxLength:y("PASSWORD_MAX_LENGTH",128)}),i,c,l;if(t){let f=r$1.redis;i=new R(f,{maxAttempts:y("LOCKOUT_MAX_ATTEMPTS",5),lockDuration:y("LOCKOUT_DURATION_MINUTES",15)*60*1e3}),c=new v(f,{"auth:login":{window:y("RATE_LIMIT_AUTH_WINDOW_MS",9e5),max:y("RATE_LIMIT_AUTH_MAX_REQUESTS",10)},"api:general":{window:y("RATE_LIMIT_WINDOW_MS",6e4),max:y("RATE_LIMIT_MAX_REQUESTS",100)}}),l=new bb(f,y("AUDIT_LOG_RETENTION_DAYS",30));}else i=new I({maxAttempts:y("LOCKOUT_MAX_ATTEMPTS",5),lockDuration:y("LOCKOUT_DURATION_MINUTES",15)*60*1e3}),c=new ab({"auth:login":{window:y("RATE_LIMIT_AUTH_WINDOW_MS",9e5),max:y("RATE_LIMIT_AUTH_MAX_REQUESTS",10)},"api:general":{window:y("RATE_LIMIT_WINDOW_MS",6e4),max:y("RATE_LIMIT_MAX_REQUESTS",100)}}),l=P("AUDIT_LOG_ENABLED",true)?new db(y("AUDIT_LOG_RETENTION_DAYS",30)):void 0;let p=new eb({redis:r$1,email:o,jwtSecret:b("APP_SECRET","change-me"),jwtExpiresIn:b("JWT_EXPIRES_IN","24h"),jwtIssuer:b("JWT_ISSUER","kyro-cms"),jwtAudience:b("JWT_AUDIENCE","kyro-cms-client"),passwordPolicy:n,lockout:i,rateLimiter:c,auditLogger:l,baseUrl:b("EMAIL_BASE_URL","http://localhost:4321"),emailVerificationRequired:P("EMAIL_VERIFICATION_REQUIRED",true)}),g=t?"distributed":s||Be();return {authAdapter:r$1,databaseType:g,email:o,passwordPolicy:n,lockout:i,rateLimiter:c,auditLogger:l,routes:p}}var $e=G().catch(s=>(console.warn("[AuthConfig] Failed to initialize auth config:",s.message),null));var ro=12,oo="24h",so="7d",B=class{adapter;config;constructor(e,t){this.adapter=e,this.config={secret:t.secret,expiresIn:t.expiresIn??oo,refreshExpiresIn:t.refreshExpiresIn??so,issuer:t.issuer??"kyro-cms",audience:t.audience??[],saltRounds:t.saltRounds??ro};}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-OD67R5JS.js');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-OD67R5JS.js'),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-ZEEHSMAG.js');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 no(s,e){return new B(s,e)}g();g();function N(){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={...N(),...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 io(s,e){return new $(s,e)}function ao(s){return s==="published"}function co(s){return s==="draft"}function lo(s){return s==="archived"}g();function uo(s){return s?Array.isArray(s)?s:Object.values(s):[]}function po(s){return s?Array.isArray(s)?s:Object.values(s):[]}function ze(s){return {collections:uo(s.collections),globals:po(s.globals),adapter:s.adapter,storage:s.storage,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 go=ze;g();function mo(s){let{siteSettings:e,seoSettings:t,title:r,description:o,image:n,url:i}=s;if(!e)return "";let c=e.siteName||"",l=r||t?.defaultTitle||c,p=t?.titleTemplate,g=t?.separator||" | ",m=t?.siteNameInTitle!==false,f=p?p.replace(/\{\{title\}\}/g,l).replace(/\{\{siteName\}\}/g,m?c:"").replace(/\{\{separator\}\}/g,g).replace(/\s+/g," ").trim():l,w=o||t?.defaultDescription||e.siteDescription||"",h=n||e.siteOgImage?.url||"",V=i||e.siteUrl||"",A=`
|
|
3
3
|
<title>${f}</title>
|
|
4
4
|
<meta name="description" content="${w}">
|
package/dist/rest/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var chunkOTSDT3NH_cjs=require('../chunk-OTSDT3NH.cjs');require('../chunk-XTTGHN3D.cjs'),require('../chunk-HPYH7GTS.cjs'),require('../chunk-OPTVCCQQ.cjs'),require('../chunk-O4YE57OS.cjs'),require('../chunk-MCIZG4A3.cjs'),require('../chunk-35PGCW3S.cjs'),require('../chunk-UNYXWPLZ.cjs'),require('../chunk-PITMDQYN.cjs'),require('../chunk-GIS6X43A.cjs'),require('../chunk-LEBM6ZSZ.cjs'),require('../chunk-GNEVCEJU.cjs'),require('../chunk-ZO3YB5DK.cjs'),require('../chunk-3VXEK5ZW.cjs'),require('../chunk-EZIDQBXI.cjs'),require('../chunk-LQ3YZTPU.cjs'),require('../chunk-MVX2PYJJ.cjs'),require('../chunk-FSL3NLRT.cjs'),require('../chunk-ZHA446FA.cjs'),require('../chunk-ZQETJ4T4.cjs'),require('../chunk-XBQ6HV3T.cjs'),require('../chunk-7JWQ2PZP.cjs'),require('../chunk-NGNJSUGL.cjs'),require('../chunk-SOCBJPYB.cjs'),require('../chunk-GNOSG3PK.cjs'),require('../chunk-BCEE4NBZ.cjs'),require('../chunk-LY7N3UHH.cjs'),require('../chunk-BAVN7VDR.cjs'),require('../chunk-VRZC4TTF.cjs'),require('../chunk-7DUKWHRN.cjs'),require('../chunk-HTYVI2HK.cjs'),require('../chunk-ZOVH6QT5.cjs'),require('../chunk-7WMMKGEO.cjs'),require('../chunk-BUNLC3II.cjs');Object.defineProperty(exports,"createKyroApp",{enumerable:true,get:function(){return chunkOTSDT3NH_cjs.ib}});Object.defineProperty(exports,"createRESTAPI",{enumerable:true,get:function(){return chunkOTSDT3NH_cjs.jb}});
|
package/dist/rest/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{ib as createKyroApp,jb as createRESTAPI}from'../chunk-
|
|
1
|
+
export{ib as createKyroApp,jb as createRESTAPI}from'../chunk-2ZACCXDM.js';import'../chunk-KWGB3YNI.js';import'../chunk-OLRCZ6E3.js';import'../chunk-N6MNQIQU.js';import'../chunk-6TPICJ2L.js';import'../chunk-YENNL5HG.js';import'../chunk-W45TLOOT.js';import'../chunk-IKGVPXMK.js';import'../chunk-YUUXFD73.js';import'../chunk-LVBHOZZF.js';import'../chunk-OBYAIJVU.js';import'../chunk-JRUQ5ABB.js';import'../chunk-CIVA6SKW.js';import'../chunk-WPM6LFCY.js';import'../chunk-U6KFONKM.js';import'../chunk-TYQYKKWJ.js';import'../chunk-L2QXP26Q.js';import'../chunk-AWQGDMOE.js';import'../chunk-GQGFNTDZ.js';import'../chunk-4OMQURN7.js';import'../chunk-ZWDBPEXL.js';import'../chunk-47CXBWMA.js';import'../chunk-EML5FDUU.js';import'../chunk-637PTUHF.js';import'../chunk-N5POANYV.js';import'../chunk-HRAY65XH.js';import'../chunk-2HA6EKXX.js';import'../chunk-FLMUMPDE.js';import'../chunk-3NSZZCOJ.js';import'../chunk-5ZEYOFAK.js';import'../chunk-7NH7H3WA.js';import'../chunk-VVVCCB6R.js';import'../chunk-TBHNE4VV.js';import'../chunk-Y2YAKDEQ.js';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kyro-cms/core",
|
|
3
|
-
"version": "0.12.
|
|
3
|
+
"version": "0.12.68",
|
|
4
4
|
"description": "Astro-native headless CMS with multi-database adapters, multi-protocol APIs, and multi-vendor support",
|
|
5
5
|
"engines": {
|
|
6
6
|
"node": ">=22"
|
|
@@ -191,7 +191,7 @@
|
|
|
191
191
|
"ws": "^8.18.0",
|
|
192
192
|
"zod": "^3.24.0",
|
|
193
193
|
"zod-to-json-schema": "^3.25.2",
|
|
194
|
-
"@kyro-cms/ai": "0.12.
|
|
194
|
+
"@kyro-cms/ai": "0.12.68"
|
|
195
195
|
},
|
|
196
196
|
"devDependencies": {
|
|
197
197
|
"@tailwindcss/vite": "^4.0.0",
|