@shware/security 3.0.0 → 3.0.1
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/auth/index.cjs.map +1 -1
- package/dist/auth/index.d.cts +1 -1
- package/dist/auth/index.d.cts.map +1 -1
- package/dist/auth/index.d.mts +1 -1
- package/dist/auth/index.d.mts.map +1 -1
- package/dist/auth/index.mjs.map +1 -1
- package/dist/email/schema.d.cts.map +1 -1
- package/dist/email/schema.d.mts.map +1 -1
- package/dist/oauth2/client.cjs.map +1 -1
- package/dist/oauth2/client.d.cts +1 -1
- package/dist/oauth2/client.d.cts.map +1 -1
- package/dist/oauth2/client.d.mts +1 -1
- package/dist/oauth2/client.d.mts.map +1 -1
- package/dist/oauth2/client.mjs.map +1 -1
- package/dist/oauth2/provider/github.cjs +1 -1
- package/dist/oauth2/provider/github.cjs.map +1 -1
- package/dist/oauth2/provider/github.mjs +1 -1
- package/dist/oauth2/provider/github.mjs.map +1 -1
- package/dist/oauth2/provider/x.cjs +1 -1
- package/dist/oauth2/provider/x.cjs.map +1 -1
- package/dist/oauth2/provider/x.mjs +1 -1
- package/dist/oauth2/provider/x.mjs.map +1 -1
- package/dist/session/common.cjs +1 -1
- package/dist/session/common.cjs.map +1 -1
- package/dist/session/common.mjs +1 -1
- package/dist/session/common.mjs.map +1 -1
- package/dist/session/db.cjs.map +1 -1
- package/dist/session/db.d.cts +1 -1
- package/dist/session/db.d.cts.map +1 -1
- package/dist/session/db.d.mts +1 -1
- package/dist/session/db.d.mts.map +1 -1
- package/dist/session/db.mjs.map +1 -1
- package/dist/session/map-session.cjs.map +1 -1
- package/dist/session/map-session.d.cts +2 -2
- package/dist/session/map-session.d.cts.map +1 -1
- package/dist/session/map-session.d.mts +2 -2
- package/dist/session/map-session.d.mts.map +1 -1
- package/dist/session/map-session.mjs.map +1 -1
- package/dist/session/redis.cjs +3 -3
- package/dist/session/redis.cjs.map +1 -1
- package/dist/session/redis.mjs +3 -3
- package/dist/session/redis.mjs.map +1 -1
- package/dist/utils/valid.cjs +1 -1
- package/dist/utils/valid.cjs.map +1 -1
- package/dist/utils/valid.mjs +1 -1
- package/dist/utils/valid.mjs.map +1 -1
- package/package.json +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"redis.mjs","names":[],"sources":["../../src/session/redis.ts"],"sourcesContent":["import type { Redis } from 'ioredis';\nimport { PRINCIPAL_NAME_INDEX_NAME, SPRING_SECURITY_CONTEXT, resolveIndexesFor } from './common';\nimport { MapSession } from './map-session';\nimport type { KVRepository, Namespace, Session, SessionRepository } from './types';\n\nconst CREATION_TIME_KEY = 'creationTime';\nconst LAST_ACCESSED_TIME_KEY = 'lastAccessedTime';\nconst MAX_INACTIVE_INTERVAL_KEY = 'maxInactiveInterval';\nconst ATTRIBUTE_PREFIX = 'sessionAttr:';\nconst SESSION_EXPIRES_PREFIX = 'expires:';\n\nclass RedisSession implements Session {\n private readonly cached: MapSession;\n\n public isNew: boolean;\n public delta = new Map<string, string | number | null>();\n public originalSessionId: string;\n public originalPrincipalName: string | null;\n public originalLastAccessTime: number | null = null;\n\n constructor(cached: MapSession, isNew: boolean) {\n this.cached = cached;\n this.isNew = isNew;\n this.originalSessionId = cached.getId();\n this.originalPrincipalName = resolveIndexesFor(this);\n\n if (isNew) {\n this.delta.set(CREATION_TIME_KEY, cached.getCreationTime());\n this.delta.set(LAST_ACCESSED_TIME_KEY, cached.getLastAccessedTime());\n this.delta.set(MAX_INACTIVE_INTERVAL_KEY, cached.getMaxInactiveInterval());\n this.cached.getAttributeNames().forEach((name) => {\n const value = this.cached.getAttribute(name);\n if (value) this.delta.set(this.getSessionAttrNameKey(name), value);\n });\n }\n }\n\n getSessionAttrNameKey(name: string) {\n return ATTRIBUTE_PREFIX + name;\n }\n\n // override\n setLastAccessedTime(lastAccessedTime: number) {\n this.cached.setLastAccessedTime(lastAccessedTime);\n this.delta.set(LAST_ACCESSED_TIME_KEY, lastAccessedTime);\n }\n\n isExpired() {\n return this.cached.isExpired();\n }\n\n getCreationTime() {\n return this.cached.getCreationTime();\n }\n\n getId() {\n return this.cached.getId();\n }\n\n changeSessionId() {\n return this.cached.changeSessionId();\n }\n\n getLastAccessedTime() {\n return this.cached.getLastAccessedTime();\n }\n\n setMaxInactiveInterval(interval: number) {\n this.cached.setMaxInactiveInterval(interval);\n this.delta.set(MAX_INACTIVE_INTERVAL_KEY, interval);\n }\n\n getMaxInactiveInterval() {\n return this.cached.getMaxInactiveInterval();\n }\n\n getAttribute(name: string) {\n return this.cached.getAttribute(name);\n }\n\n getAttributeNames() {\n return this.cached.getAttributeNames();\n }\n\n setAttribute(name: string, value: string) {\n this.cached.setAttribute(name, value);\n this.delta.set(this.getSessionAttrNameKey(name), value);\n }\n\n removeAttribute(name: string) {\n this.cached.removeAttribute(name);\n this.delta.set(this.getSessionAttrNameKey(name), null);\n }\n}\n\ninterface RedisSessionExpirationStore {\n save(session: RedisSession): Promise<void>;\n remove(sessionId: string): Promise<void>;\n rename(session: RedisSession): Promise<void>;\n cleanupExpiredSessions(cleanupCount?: number): Promise<void>;\n}\n\nclass SortedSetRedisSessionExpirationStore implements RedisSessionExpirationStore {\n private readonly redis: Redis;\n private readonly namespace: Namespace;\n private readonly expirationsKey: string;\n\n constructor(redis: Redis, namespace: Namespace) {\n this.redis = redis;\n this.namespace = namespace;\n this.expirationsKey = `${this.namespace}:sessions:expirations`;\n }\n\n getSessionKey(sessionId: string) {\n return `${this.namespace}:sessions:${sessionId}`;\n }\n\n async save(session: RedisSession) {\n const expirationInMillis =\n session.getLastAccessedTime() + session.getMaxInactiveInterval() * 1000;\n await this.redis.zadd(this.expirationsKey, expirationInMillis, session.getId());\n }\n\n async remove(sessionId: string) {\n await this.redis.zrem(this.expirationsKey, sessionId);\n }\n\n async rename(session: RedisSession) {\n if (session.originalSessionId === null || session.originalSessionId === session.getId()) return;\n await this.remove(session.originalSessionId);\n await this.save(session);\n }\n\n async cleanupExpiredSessions(cleanupCount = 100) {\n const key = this.expirationsKey;\n const score = Date.now();\n const sessionIds = await this.redis.zrevrangebyscore(key, score, 0, 'LIMIT', 0, cleanupCount);\n if (sessionIds.length === 0) return;\n for (const sessionId of sessionIds) {\n const sessionKey = this.getSessionKey(sessionId);\n // Checks if the session exists. By trying to access the session we only trigger a deletion\n // if the TTL is expired.\n await this.redis.exists(sessionKey);\n }\n }\n}\n\n// <spring:session:sessions:uuid, hash<session>> + 300s\n// <spring:session:sessions:expirations, sorted_set<uuid>>\n// <spring:session:sessions:expires:uuid, string<empty>>: for expire check & event\nexport class RedisIndexedSessionRepository implements SessionRepository<RedisSession> {\n private readonly redis: Redis;\n private readonly namespace: Namespace;\n private readonly expirationStore: RedisSessionExpirationStore;\n\n private defaultMaxInactiveInterval = 1800;\n\n constructor(redis: Redis, namespace: Namespace = 'spring:session') {\n this.redis = redis;\n this.namespace = namespace;\n this.expirationStore = new SortedSetRedisSessionExpirationStore(redis, namespace);\n }\n\n setDefaultMaxInactiveInterval(interval: number) {\n this.defaultMaxInactiveInterval = interval;\n }\n\n private getSessionKey(sessionId: string) {\n return `${this.namespace}:sessions:${sessionId}`;\n }\n\n private getExpiredKey(sessionId: string) {\n return `${this.namespace}:sessions:expires:${sessionId}`;\n }\n\n private getSessionAttrNameKey(name: string) {\n return ATTRIBUTE_PREFIX + name;\n }\n\n private getPrincipalKey(principalName: string) {\n return `${this.namespace}:index:${PRINCIPAL_NAME_INDEX_NAME}:${principalName}`;\n }\n\n private async getSession(id: string, allowExpired: boolean): Promise<RedisSession | null> {\n const key = this.getSessionKey(id);\n const entries = await this.redis.hgetall(key);\n if (!entries || Object.keys(entries).length === 0) return null;\n const loaded = new MapSession(id);\n if (!entries.creationTime) throw new Error('creationTime attribute not found');\n if (!entries.lastAccessedTime) throw new Error('lastAccessedTime attribute not found');\n if (!entries.maxInactiveInterval) throw new Error('maxInactiveInterval attribute not found');\n\n loaded.setCreationTime(Number(entries.creationTime));\n loaded.setLastAccessedTime(Number(entries.lastAccessedTime));\n loaded.setMaxInactiveInterval(Number(entries.maxInactiveInterval));\n\n for (const [key, value] of Object.entries(entries)) {\n if (key.startsWith(ATTRIBUTE_PREFIX)) {\n loaded.setAttribute(key.slice(ATTRIBUTE_PREFIX.length), value);\n }\n }\n\n if (!allowExpired && loaded.isExpired()) return null;\n const result = new RedisSession(loaded, false);\n result.originalLastAccessTime = loaded.getLastAccessedTime();\n return result;\n }\n\n private async saveDelta(session: RedisSession) {\n if (session.delta.size === 0) return;\n const sessionId = session.getId();\n const delta = new Map<string, string | number>();\n const removes: string[] = [];\n session.delta.forEach((value, key) => {\n if (value !== null) delta.set(key, value);\n else removes.push(key);\n });\n\n if (delta.size !== 0) {\n await this.redis.hset(this.getSessionKey(sessionId), delta);\n }\n if (removes.length !== 0) {\n await this.redis.hdel(this.getSessionKey(sessionId), ...removes);\n }\n\n const principalSessionKey = this.getSessionAttrNameKey(PRINCIPAL_NAME_INDEX_NAME);\n const securityPrincipalSessionKey = this.getSessionAttrNameKey(SPRING_SECURITY_CONTEXT);\n if (session.delta.has(principalSessionKey) || session.delta.has(securityPrincipalSessionKey)) {\n if (session.originalPrincipalName !== null) {\n const originalPrincipalRedisKey = this.getPrincipalKey(session.originalPrincipalName);\n await this.redis.srem(originalPrincipalRedisKey, sessionId);\n }\n const principal = resolveIndexesFor(session);\n session.originalPrincipalName = principal;\n if (principal !== null) {\n const principalRedisKey = this.getPrincipalKey(principal);\n await this.redis.sadd(principalRedisKey, sessionId);\n }\n }\n\n if (session.isNew) {\n // here your can send session created message to channel\n session.isNew = false;\n }\n\n const sessionExpireInSeconds = session.getMaxInactiveInterval();\n\n // createShadowKey start\n const keyToExpire = SESSION_EXPIRES_PREFIX + session.getId();\n const sessionKey = this.getSessionKey(keyToExpire);\n\n if (sessionExpireInSeconds < 0) {\n await this.redis.append(sessionKey, '');\n await this.redis.persist(sessionKey);\n await this.redis.persist(this.getSessionKey(session.getId()));\n } else if (sessionExpireInSeconds === 0) {\n await this.redis.del(sessionKey);\n } else {\n await this.redis.append(sessionKey, '');\n await this.redis.expire(sessionKey, sessionExpireInSeconds);\n }\n // createShadowKey end\n\n if (sessionExpireInSeconds > 0) {\n const fiveMinutesAfterExpires = sessionExpireInSeconds + 5 * 60;\n await this.redis.expire(this.getSessionKey(session.getId()), fiveMinutesAfterExpires);\n }\n\n await this.expirationStore.save(session);\n session.delta.clear();\n }\n\n private async saveChangeSessionId(session: RedisSession) {\n const sessionId = session.getId();\n if (sessionId === session.originalSessionId) return;\n if (!session.isNew) {\n const originalSessionIdKey = this.getSessionKey(session.originalSessionId);\n const sessionIdKey = this.getSessionKey(sessionId);\n const originalExpiredKey = this.getExpiredKey(session.originalSessionId);\n const expiredKey = this.getExpiredKey(sessionId);\n\n await this.redis.rename(originalSessionIdKey, sessionIdKey);\n await this.redis.rename(originalExpiredKey, expiredKey);\n\n if (session.originalPrincipalName !== null) {\n const originalPrincipalRedisKey = this.getPrincipalKey(session.originalPrincipalName);\n await this.redis.srem(originalPrincipalRedisKey, session.originalSessionId);\n await this.redis.sadd(originalPrincipalRedisKey, sessionId);\n }\n await this.expirationStore.rename(session);\n }\n session.originalSessionId = sessionId;\n }\n\n // override\n createSession() {\n const cached = new MapSession();\n cached.setMaxInactiveInterval(this.defaultMaxInactiveInterval);\n return new RedisSession(cached, true);\n }\n\n async save(session: RedisSession) {\n await this.saveChangeSessionId(session);\n await this.saveDelta(session);\n }\n\n async findById(sessionId: string): Promise<RedisSession | null> {\n return this.getSession(sessionId, false);\n }\n\n async deleteById(sessionId: string) {\n const session = await this.getSession(sessionId, true);\n if (!session) return;\n // 1. cleanup index\n const principal = resolveIndexesFor(session);\n if (principal !== null) {\n await this.redis.srem(this.getPrincipalKey(principal), sessionId);\n }\n // 2. delete in set\n await this.expirationStore.remove(sessionId);\n // 3. delete expired key\n const expiredKey = this.getExpiredKey(sessionId);\n await this.redis.del(expiredKey);\n\n session.setMaxInactiveInterval(0);\n await this.save(session);\n }\n\n async findByIndexNameAndIndexValue(indexName: string, indexValue: string) {\n if (indexName !== PRINCIPAL_NAME_INDEX_NAME) {\n return new Map<string, RedisSession>();\n }\n\n const principalKey = this.getPrincipalKey(indexValue);\n const sessionIds = await this.redis.smembers(principalKey);\n if (!sessionIds || sessionIds.length === 0) {\n return new Map<string, RedisSession>();\n }\n const sessions = new Map<string, RedisSession>();\n for (const sessionId of sessionIds) {\n const session = await this.findById(sessionId);\n if (session !== null) {\n sessions.set(sessionId, session);\n }\n }\n return sessions;\n }\n\n async findByPrincipalName(principalName: string) {\n return this.findByIndexNameAndIndexValue(PRINCIPAL_NAME_INDEX_NAME, principalName);\n }\n\n async cleanupExpiredSessions(cleanupCount?: number) {\n await this.expirationStore.cleanupExpiredSessions(cleanupCount);\n }\n}\n\nexport class RedisKVRepository implements KVRepository {\n private readonly redis: Redis;\n\n constructor(redis: Redis) {\n this.redis = redis;\n }\n\n async setItem(key: string, value: string, expiresIn?: number) {\n if (expiresIn) {\n await this.redis.set(key, value, 'EX', expiresIn);\n } else {\n await this.redis.set(key, value);\n }\n }\n\n async getItem(key: string): Promise<string | null> {\n return await this.redis.get(key);\n }\n\n async removeItem(key: string) {\n await this.redis.del(key);\n }\n}\n"],"mappings":";;;AAKA,MAAM,oBAAoB;AAC1B,MAAM,yBAAyB;AAC/B,MAAM,4BAA4B;AAClC,MAAM,mBAAmB;AACzB,MAAM,yBAAyB;AAE/B,IAAM,eAAN,MAAsC;CACpC;CAEA;CACA,wBAAe,IAAI,IAAoC;CACvD;CACA;CACA,yBAA+C;CAE/C,YAAY,QAAoB,OAAgB;EAC9C,KAAK,SAAS;EACd,KAAK,QAAQ;EACb,KAAK,oBAAoB,OAAO,MAAM;EACtC,KAAK,wBAAwB,kBAAkB,IAAI;EAEnD,IAAI,OAAO;GACT,KAAK,MAAM,IAAI,mBAAmB,OAAO,gBAAgB,CAAC;GAC1D,KAAK,MAAM,IAAI,wBAAwB,OAAO,oBAAoB,CAAC;GACnE,KAAK,MAAM,IAAI,2BAA2B,O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["import type { Redis } from 'ioredis';\nimport { PRINCIPAL_NAME_INDEX_NAME, SPRING_SECURITY_CONTEXT, resolveIndexesFor } from './common';\nimport { MapSession } from './map-session';\nimport type { KVRepository, Namespace, Session, SessionRepository } from './types';\n\nconst CREATION_TIME_KEY = 'creationTime';\nconst LAST_ACCESSED_TIME_KEY = 'lastAccessedTime';\nconst MAX_INACTIVE_INTERVAL_KEY = 'maxInactiveInterval';\nconst ATTRIBUTE_PREFIX = 'sessionAttr:';\nconst SESSION_EXPIRES_PREFIX = 'expires:';\n\nclass RedisSession implements Session {\n private readonly cached: MapSession;\n\n public isNew: boolean;\n public delta = new Map<string, string | number | null>();\n public originalSessionId: string;\n public originalPrincipalName: string | null;\n public originalLastAccessTime: number | null = null;\n\n constructor(cached: MapSession, isNew: boolean) {\n this.cached = cached;\n this.isNew = isNew;\n this.originalSessionId = cached.getId();\n this.originalPrincipalName = resolveIndexesFor(this);\n\n if (isNew) {\n this.delta.set(CREATION_TIME_KEY, cached.getCreationTime());\n this.delta.set(LAST_ACCESSED_TIME_KEY, cached.getLastAccessedTime());\n this.delta.set(MAX_INACTIVE_INTERVAL_KEY, cached.getMaxInactiveInterval());\n this.cached.getAttributeNames().forEach((name) => {\n const value = this.cached.getAttribute(name);\n if (value) this.delta.set(this.getSessionAttrNameKey(name), value);\n });\n }\n }\n\n getSessionAttrNameKey(name: string) {\n return ATTRIBUTE_PREFIX + name;\n }\n\n // override\n setLastAccessedTime(lastAccessedTime: number) {\n this.cached.setLastAccessedTime(lastAccessedTime);\n this.delta.set(LAST_ACCESSED_TIME_KEY, lastAccessedTime);\n }\n\n isExpired() {\n return this.cached.isExpired();\n }\n\n getCreationTime() {\n return this.cached.getCreationTime();\n }\n\n getId() {\n return this.cached.getId();\n }\n\n changeSessionId() {\n return this.cached.changeSessionId();\n }\n\n getLastAccessedTime() {\n return this.cached.getLastAccessedTime();\n }\n\n setMaxInactiveInterval(interval: number) {\n this.cached.setMaxInactiveInterval(interval);\n this.delta.set(MAX_INACTIVE_INTERVAL_KEY, interval);\n }\n\n getMaxInactiveInterval() {\n return this.cached.getMaxInactiveInterval();\n }\n\n getAttribute(name: string) {\n return this.cached.getAttribute(name);\n }\n\n getAttributeNames() {\n return this.cached.getAttributeNames();\n }\n\n setAttribute(name: string, value: string) {\n this.cached.setAttribute(name, value);\n this.delta.set(this.getSessionAttrNameKey(name), value);\n }\n\n removeAttribute(name: string) {\n this.cached.removeAttribute(name);\n this.delta.set(this.getSessionAttrNameKey(name), null);\n }\n}\n\ninterface RedisSessionExpirationStore {\n save(session: RedisSession): Promise<void>;\n remove(sessionId: string): Promise<void>;\n rename(session: RedisSession): Promise<void>;\n cleanupExpiredSessions(cleanupCount?: number): Promise<void>;\n}\n\nclass SortedSetRedisSessionExpirationStore implements RedisSessionExpirationStore {\n private readonly redis: Redis;\n private readonly namespace: Namespace;\n private readonly expirationsKey: string;\n\n constructor(redis: Redis, namespace: Namespace) {\n this.redis = redis;\n this.namespace = namespace;\n this.expirationsKey = `${this.namespace}:sessions:expirations`;\n }\n\n getSessionKey(sessionId: string) {\n return `${this.namespace}:sessions:${sessionId}`;\n }\n\n async save(session: RedisSession) {\n const expirationInMillis =\n session.getLastAccessedTime() + session.getMaxInactiveInterval() * 1000;\n await this.redis.zadd(this.expirationsKey, expirationInMillis, session.getId());\n }\n\n async remove(sessionId: string) {\n await this.redis.zrem(this.expirationsKey, sessionId);\n }\n\n async rename(session: RedisSession) {\n if (session.originalSessionId === session.getId()) return;\n await this.remove(session.originalSessionId);\n await this.save(session);\n }\n\n async cleanupExpiredSessions(cleanupCount = 100) {\n const key = this.expirationsKey;\n const score = Date.now();\n const sessionIds = await this.redis.zrevrangebyscore(key, score, 0, 'LIMIT', 0, cleanupCount);\n if (sessionIds.length === 0) return;\n for (const sessionId of sessionIds) {\n const sessionKey = this.getSessionKey(sessionId);\n // Checks if the session exists. By trying to access the session we only trigger a deletion\n // if the TTL is expired.\n await this.redis.exists(sessionKey);\n }\n }\n}\n\n// <spring:session:sessions:uuid, hash<session>> + 300s\n// <spring:session:sessions:expirations, sorted_set<uuid>>\n// <spring:session:sessions:expires:uuid, string<empty>>: for expire check & event\nexport class RedisIndexedSessionRepository implements SessionRepository<RedisSession> {\n private readonly redis: Redis;\n private readonly namespace: Namespace;\n private readonly expirationStore: RedisSessionExpirationStore;\n\n private defaultMaxInactiveInterval = 1800;\n\n constructor(redis: Redis, namespace: Namespace = 'spring:session') {\n this.redis = redis;\n this.namespace = namespace;\n this.expirationStore = new SortedSetRedisSessionExpirationStore(redis, namespace);\n }\n\n setDefaultMaxInactiveInterval(interval: number) {\n this.defaultMaxInactiveInterval = interval;\n }\n\n private getSessionKey(sessionId: string) {\n return `${this.namespace}:sessions:${sessionId}`;\n }\n\n private getExpiredKey(sessionId: string) {\n return `${this.namespace}:sessions:expires:${sessionId}`;\n }\n\n private getSessionAttrNameKey(name: string) {\n return ATTRIBUTE_PREFIX + name;\n }\n\n private getPrincipalKey(principalName: string) {\n return `${this.namespace}:index:${PRINCIPAL_NAME_INDEX_NAME}:${principalName}`;\n }\n\n private async getSession(id: string, allowExpired: boolean): Promise<RedisSession | null> {\n const key = this.getSessionKey(id);\n const entries = await this.redis.hgetall(key);\n if (Object.keys(entries).length === 0) return null;\n const loaded = new MapSession(id);\n if (!entries.creationTime) throw new Error('creationTime attribute not found');\n if (!entries.lastAccessedTime) throw new Error('lastAccessedTime attribute not found');\n if (!entries.maxInactiveInterval) throw new Error('maxInactiveInterval attribute not found');\n\n loaded.setCreationTime(Number(entries.creationTime));\n loaded.setLastAccessedTime(Number(entries.lastAccessedTime));\n loaded.setMaxInactiveInterval(Number(entries.maxInactiveInterval));\n\n for (const [key, value] of Object.entries(entries)) {\n if (key.startsWith(ATTRIBUTE_PREFIX)) {\n loaded.setAttribute(key.slice(ATTRIBUTE_PREFIX.length), value);\n }\n }\n\n if (!allowExpired && loaded.isExpired()) return null;\n const result = new RedisSession(loaded, false);\n result.originalLastAccessTime = loaded.getLastAccessedTime();\n return result;\n }\n\n private async saveDelta(session: RedisSession) {\n if (session.delta.size === 0) return;\n const sessionId = session.getId();\n const delta = new Map<string, string | number>();\n const removes: string[] = [];\n session.delta.forEach((value, key) => {\n if (value !== null) delta.set(key, value);\n else removes.push(key);\n });\n\n if (delta.size !== 0) {\n await this.redis.hset(this.getSessionKey(sessionId), delta);\n }\n if (removes.length !== 0) {\n await this.redis.hdel(this.getSessionKey(sessionId), ...removes);\n }\n\n const principalSessionKey = this.getSessionAttrNameKey(PRINCIPAL_NAME_INDEX_NAME);\n const securityPrincipalSessionKey = this.getSessionAttrNameKey(SPRING_SECURITY_CONTEXT);\n if (session.delta.has(principalSessionKey) || session.delta.has(securityPrincipalSessionKey)) {\n if (session.originalPrincipalName !== null) {\n const originalPrincipalRedisKey = this.getPrincipalKey(session.originalPrincipalName);\n await this.redis.srem(originalPrincipalRedisKey, sessionId);\n }\n const principal = resolveIndexesFor(session);\n session.originalPrincipalName = principal;\n if (principal !== null) {\n const principalRedisKey = this.getPrincipalKey(principal);\n await this.redis.sadd(principalRedisKey, sessionId);\n }\n }\n\n if (session.isNew) {\n // here your can send session created message to channel\n session.isNew = false;\n }\n\n const sessionExpireInSeconds = session.getMaxInactiveInterval();\n\n // createShadowKey start\n const keyToExpire = SESSION_EXPIRES_PREFIX + session.getId();\n const sessionKey = this.getSessionKey(keyToExpire);\n\n if (sessionExpireInSeconds < 0) {\n await this.redis.append(sessionKey, '');\n await this.redis.persist(sessionKey);\n await this.redis.persist(this.getSessionKey(session.getId()));\n } else if (sessionExpireInSeconds === 0) {\n await this.redis.del(sessionKey);\n } else {\n await this.redis.append(sessionKey, '');\n await this.redis.expire(sessionKey, sessionExpireInSeconds);\n }\n // createShadowKey end\n\n if (sessionExpireInSeconds > 0) {\n const fiveMinutesAfterExpires = sessionExpireInSeconds + 5 * 60;\n await this.redis.expire(this.getSessionKey(session.getId()), fiveMinutesAfterExpires);\n }\n\n await this.expirationStore.save(session);\n session.delta.clear();\n }\n\n private async saveChangeSessionId(session: RedisSession) {\n const sessionId = session.getId();\n if (sessionId === session.originalSessionId) return;\n if (!session.isNew) {\n const originalSessionIdKey = this.getSessionKey(session.originalSessionId);\n const sessionIdKey = this.getSessionKey(sessionId);\n const originalExpiredKey = this.getExpiredKey(session.originalSessionId);\n const expiredKey = this.getExpiredKey(sessionId);\n\n await this.redis.rename(originalSessionIdKey, sessionIdKey);\n await this.redis.rename(originalExpiredKey, expiredKey);\n\n if (session.originalPrincipalName !== null) {\n const originalPrincipalRedisKey = this.getPrincipalKey(session.originalPrincipalName);\n await this.redis.srem(originalPrincipalRedisKey, session.originalSessionId);\n await this.redis.sadd(originalPrincipalRedisKey, sessionId);\n }\n await this.expirationStore.rename(session);\n }\n session.originalSessionId = sessionId;\n }\n\n // override\n createSession() {\n const cached = new MapSession();\n cached.setMaxInactiveInterval(this.defaultMaxInactiveInterval);\n return new RedisSession(cached, true);\n }\n\n async save(session: RedisSession) {\n await this.saveChangeSessionId(session);\n await this.saveDelta(session);\n }\n\n async findById(sessionId: string): Promise<RedisSession | null> {\n return this.getSession(sessionId, false);\n }\n\n async deleteById(sessionId: string) {\n const session = await this.getSession(sessionId, true);\n if (!session) return;\n // 1. cleanup index\n const principal = resolveIndexesFor(session);\n if (principal !== null) {\n await this.redis.srem(this.getPrincipalKey(principal), sessionId);\n }\n // 2. delete in set\n await this.expirationStore.remove(sessionId);\n // 3. delete expired key\n const expiredKey = this.getExpiredKey(sessionId);\n await this.redis.del(expiredKey);\n\n session.setMaxInactiveInterval(0);\n await this.save(session);\n }\n\n async findByIndexNameAndIndexValue(indexName: string, indexValue: string) {\n if (indexName !== PRINCIPAL_NAME_INDEX_NAME) {\n return new Map<string, RedisSession>();\n }\n\n const principalKey = this.getPrincipalKey(indexValue);\n const sessionIds = await this.redis.smembers(principalKey);\n if (sessionIds.length === 0) {\n return new Map<string, RedisSession>();\n }\n const sessions = new Map<string, RedisSession>();\n for (const sessionId of sessionIds) {\n const session = await this.findById(sessionId);\n if (session !== null) {\n sessions.set(sessionId, session);\n }\n }\n return sessions;\n }\n\n async findByPrincipalName(principalName: string) {\n return this.findByIndexNameAndIndexValue(PRINCIPAL_NAME_INDEX_NAME, principalName);\n }\n\n async cleanupExpiredSessions(cleanupCount?: number) {\n await this.expirationStore.cleanupExpiredSessions(cleanupCount);\n }\n}\n\nexport class RedisKVRepository implements KVRepository {\n private readonly redis: Redis;\n\n constructor(redis: Redis) {\n this.redis = redis;\n }\n\n async setItem(key: string, value: string, expiresIn?: number) {\n if (expiresIn) {\n await this.redis.set(key, value, 'EX', expiresIn);\n } else {\n await this.redis.set(key, value);\n }\n }\n\n async getItem(key: string): Promise<string | null> {\n return await this.redis.get(key);\n }\n\n async removeItem(key: string) {\n await this.redis.del(key);\n }\n}\n"],"mappings":";;;AAKA,MAAM,oBAAoB;AAC1B,MAAM,yBAAyB;AAC/B,MAAM,4BAA4B;AAClC,MAAM,mBAAmB;AACzB,MAAM,yBAAyB;AAE/B,IAAM,eAAN,MAAsC;CACpC;CAEA;CACA,wBAAe,IAAI,IAAoC;CACvD;CACA;CACA,yBAA+C;CAE/C,YAAY,QAAoB,OAAgB;EAC9C,KAAK,SAAS;EACd,KAAK,QAAQ;EACb,KAAK,oBAAoB,OAAO,MAAM;EACtC,KAAK,wBAAwB,kBAAkB,IAAI;EAEnD,IAAI,OAAO;GACT,KAAK,MAAM,IAAI,mBAAmB,OAAO,gBAAgB,CAAC;GAC1D,KAAK,MAAM,IAAI,wBAAwB,OAAO,oBAAoB,CAAC;GACnE,KAAK,MAAM,IAAI,2BAA2B,OAAO,uBAAuB,CAAC;GACzE,KAAK,OAAO,kBAAkB,CAAC,CAAC,SAAS,SAAS;IAChD,MAAM,QAAQ,KAAK,OAAO,aAAa,IAAI;IAC3C,IAAI,OAAO,KAAK,MAAM,IAAI,KAAK,sBAAsB,IAAI,GAAG,KAAK;GACnE,CAAC;EACH;CACF;CAEA,sBAAsB,MAAc;EAClC,OAAO,mBAAmB;CAC5B;CAGA,oBA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B;EAGvC,MAAM,eAAe,KAAK,gBAAgB,UAAU;EACpD,MAAM,aAAa,MAAM,KAAK,MAAM,SAAS,YAAY;EACzD,IAAI,WAAW,WAAW,GACxB,uBAAO,IAAI,IAA0B;EAEvC,MAAM,2BAAW,IAAI,IAA0B;EAC/C,KAAK,MAAM,aAAa,YAAY;GAClC,MAAM,UAAU,MAAM,KAAK,SAAS,SAAS;GAC7C,IAAI,YAAY,MACd,SAAS,IAAI,WAAW,OAAO;EAEnC;EACA,OAAO;CACT;CAEA,MAAM,oBAAoB,eAAuB;EAC/C,OAAO,KAAK,6BAA6B,2BAA2B,aAAa;CACnF;CAEA,MAAM,uBAAuB,cAAuB;EAClD,MAAM,KAAK,gBAAgB,uBAAuB,YAAY;CAChE;AACF;AAEA,IAAa,oBAAb,MAAuD;CACrD;CAEA,YAAY,OAAc;EACxB,KAAK,QAAQ;CACf;CAEA,MAAM,QAAQ,KAAa,OAAe,WAAoB;EAC5D,IAAI,WACF,MAAM,KAAK,MAAM,IAAI,KAAK,OAAO,MAAM,SAAS;OAEhD,MAAM,KAAK,MAAM,IAAI,KAAK,KAAK;CAEnC;CAEA,MAAM,QAAQ,KAAqC;EACjD,OAAO,MAAM,KAAK,MAAM,IAAI,GAAG;CACjC;CAEA,MAAM,WAAW,KAAa;EAC5B,MAAM,KAAK,MAAM,IAAI,GAAG;CAC1B;AACF"}
|
package/dist/utils/valid.cjs
CHANGED
|
@@ -27,7 +27,7 @@ function valid(schema, json) {
|
|
|
27
27
|
fieldViolations: result.error.issues.map(({ code, path, message }) => ({
|
|
28
28
|
field: path.join("."),
|
|
29
29
|
description: message,
|
|
30
|
-
reason: code
|
|
30
|
+
reason: code.toUpperCase(),
|
|
31
31
|
localizedMessage: {
|
|
32
32
|
locale: "en-US",
|
|
33
33
|
message
|
package/dist/utils/valid.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"valid.cjs","names":[],"sources":["../../src/utils/valid.ts"],"sourcesContent":["import type { ZodType, output } from 'zod';\nimport type { ZodMiniType, output as outputMini } from 'zod/mini';\n\ntype ErrorBody = {\n error: {\n code: number;\n status: string;\n message: string;\n details: unknown[];\n };\n};\n\nexport function invalidArgument(reason: string): ErrorBody {\n return {\n error: {\n code: 400,\n status: 'INVALID_ARGUMENT',\n message: 'Invalid verification code',\n details: [{ '@type': 'type.googleapis.com/google.rpc.ErrorInfo', reason }],\n },\n };\n}\n\ntype Result<S extends ZodType | ZodMiniType> =\n | { error: null; data: S extends ZodType ? output<S> : outputMini<S> }\n | { error: ErrorBody; data: null };\n\nexport function valid<S extends ZodType | ZodMiniType>(schema: S, json: unknown): Result<S> {\n const result = schema.safeParse(json);\n if (result.success) {\n return {\n error: null,\n data: result.data as S extends ZodType ? output<S> : outputMini<S>,\n };\n }\n\n const fieldViolations = result.error.issues.map(({ code, path, message }) => ({\n field: path.join('.'),\n description: message,\n reason: code
|
|
1
|
+
{"version":3,"file":"valid.cjs","names":[],"sources":["../../src/utils/valid.ts"],"sourcesContent":["import type { ZodType, output } from 'zod';\nimport type { ZodMiniType, output as outputMini } from 'zod/mini';\n\ntype ErrorBody = {\n error: {\n code: number;\n status: string;\n message: string;\n details: unknown[];\n };\n};\n\nexport function invalidArgument(reason: string): ErrorBody {\n return {\n error: {\n code: 400,\n status: 'INVALID_ARGUMENT',\n message: 'Invalid verification code',\n details: [{ '@type': 'type.googleapis.com/google.rpc.ErrorInfo', reason }],\n },\n };\n}\n\ntype Result<S extends ZodType | ZodMiniType> =\n | { error: null; data: S extends ZodType ? output<S> : outputMini<S> }\n | { error: ErrorBody; data: null };\n\nexport function valid<S extends ZodType | ZodMiniType>(schema: S, json: unknown): Result<S> {\n const result = schema.safeParse(json);\n if (result.success) {\n return {\n error: null,\n data: result.data as S extends ZodType ? output<S> : outputMini<S>,\n };\n }\n\n const fieldViolations = result.error.issues.map(({ code, path, message }) => ({\n field: path.join('.'),\n description: message,\n reason: code.toUpperCase(),\n localizedMessage: { locale: 'en-US', message: message },\n }));\n\n const error = {\n error: {\n code: 400,\n status: 'INVALID_ARGUMENT',\n message: 'Invalid request',\n details: [{ '@type': 'type.googleapis.com/google.rpc.BadRequest', fieldViolations }],\n },\n };\n\n return { error, data: null };\n}\n\nexport async function verifyTurnstileToken(secret: string, token: string) {\n const response = await fetch('https://challenges.cloudflare.com/turnstile/v0/siteverify', {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({ secret, response: token }),\n });\n\n const data = (await response.json()) as { success: boolean };\n if (data.success) return { error: null };\n return { error: invalidArgument('TURNSTILE_VERIFICATION_FAILED') };\n}\n"],"mappings":";;AAYA,SAAgB,gBAAgB,QAA2B;CACzD,OAAO,EACL,OAAO;EACL,MAAM;EACN,QAAQ;EACR,SAAS;EACT,SAAS,CAAC;GAAE,SAAS;GAA4C;EAAO,CAAC;CAC3E,EACF;AACF;AAMA,SAAgB,MAAuC,QAAW,MAA0B;CAC1F,MAAM,SAAS,OAAO,UAAU,IAAI;CACpC,IAAI,OAAO,SACT,OAAO;EACL,OAAO;EACP,MAAM,OAAO;CACf;CAmBF,OAAO;EAAE,OAAA,EARP,OAAO;GACL,MAAM;GACN,QAAQ;GACR,SAAS;GACT,SAAS,CAAC;IAAE,SAAS;IAA6C,iBAZ9C,OAAO,MAAM,OAAO,KAAK,EAAE,MAAM,MAAM,eAAe;KAC5E,OAAO,KAAK,KAAK,GAAG;KACpB,aAAa;KACb,QAAQ,KAAK,YAAY;KACzB,kBAAkB;MAAE,QAAQ;MAAkB;KAAQ;IACxD,EAOoF;GAAE,CAAC;EACrF,EAGW;EAAG,MAAM;CAAK;AAC7B;AAEA,eAAsB,qBAAqB,QAAgB,OAAe;CAQxE,KAAI,OADgB,MANG,MAAM,6DAA6D;EACxF,QAAQ;EACR,SAAS,EAAE,gBAAgB,oCAAoC;EAC/D,MAAM,IAAI,gBAAgB;GAAE;GAAQ,UAAU;EAAM,CAAC;CACvD,CAAC,EAAA,CAE4B,KAAK,EAAA,CACzB,SAAS,OAAO,EAAE,OAAO,KAAK;CACvC,OAAO,EAAE,OAAO,gBAAgB,+BAA+B,EAAE;AACnE"}
|
package/dist/utils/valid.mjs
CHANGED
|
@@ -26,7 +26,7 @@ function valid(schema, json) {
|
|
|
26
26
|
fieldViolations: result.error.issues.map(({ code, path, message }) => ({
|
|
27
27
|
field: path.join("."),
|
|
28
28
|
description: message,
|
|
29
|
-
reason: code
|
|
29
|
+
reason: code.toUpperCase(),
|
|
30
30
|
localizedMessage: {
|
|
31
31
|
locale: "en-US",
|
|
32
32
|
message
|
package/dist/utils/valid.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"valid.mjs","names":[],"sources":["../../src/utils/valid.ts"],"sourcesContent":["import type { ZodType, output } from 'zod';\nimport type { ZodMiniType, output as outputMini } from 'zod/mini';\n\ntype ErrorBody = {\n error: {\n code: number;\n status: string;\n message: string;\n details: unknown[];\n };\n};\n\nexport function invalidArgument(reason: string): ErrorBody {\n return {\n error: {\n code: 400,\n status: 'INVALID_ARGUMENT',\n message: 'Invalid verification code',\n details: [{ '@type': 'type.googleapis.com/google.rpc.ErrorInfo', reason }],\n },\n };\n}\n\ntype Result<S extends ZodType | ZodMiniType> =\n | { error: null; data: S extends ZodType ? output<S> : outputMini<S> }\n | { error: ErrorBody; data: null };\n\nexport function valid<S extends ZodType | ZodMiniType>(schema: S, json: unknown): Result<S> {\n const result = schema.safeParse(json);\n if (result.success) {\n return {\n error: null,\n data: result.data as S extends ZodType ? output<S> : outputMini<S>,\n };\n }\n\n const fieldViolations = result.error.issues.map(({ code, path, message }) => ({\n field: path.join('.'),\n description: message,\n reason: code
|
|
1
|
+
{"version":3,"file":"valid.mjs","names":[],"sources":["../../src/utils/valid.ts"],"sourcesContent":["import type { ZodType, output } from 'zod';\nimport type { ZodMiniType, output as outputMini } from 'zod/mini';\n\ntype ErrorBody = {\n error: {\n code: number;\n status: string;\n message: string;\n details: unknown[];\n };\n};\n\nexport function invalidArgument(reason: string): ErrorBody {\n return {\n error: {\n code: 400,\n status: 'INVALID_ARGUMENT',\n message: 'Invalid verification code',\n details: [{ '@type': 'type.googleapis.com/google.rpc.ErrorInfo', reason }],\n },\n };\n}\n\ntype Result<S extends ZodType | ZodMiniType> =\n | { error: null; data: S extends ZodType ? output<S> : outputMini<S> }\n | { error: ErrorBody; data: null };\n\nexport function valid<S extends ZodType | ZodMiniType>(schema: S, json: unknown): Result<S> {\n const result = schema.safeParse(json);\n if (result.success) {\n return {\n error: null,\n data: result.data as S extends ZodType ? output<S> : outputMini<S>,\n };\n }\n\n const fieldViolations = result.error.issues.map(({ code, path, message }) => ({\n field: path.join('.'),\n description: message,\n reason: code.toUpperCase(),\n localizedMessage: { locale: 'en-US', message: message },\n }));\n\n const error = {\n error: {\n code: 400,\n status: 'INVALID_ARGUMENT',\n message: 'Invalid request',\n details: [{ '@type': 'type.googleapis.com/google.rpc.BadRequest', fieldViolations }],\n },\n };\n\n return { error, data: null };\n}\n\nexport async function verifyTurnstileToken(secret: string, token: string) {\n const response = await fetch('https://challenges.cloudflare.com/turnstile/v0/siteverify', {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({ secret, response: token }),\n });\n\n const data = (await response.json()) as { success: boolean };\n if (data.success) return { error: null };\n return { error: invalidArgument('TURNSTILE_VERIFICATION_FAILED') };\n}\n"],"mappings":";AAYA,SAAgB,gBAAgB,QAA2B;CACzD,OAAO,EACL,OAAO;EACL,MAAM;EACN,QAAQ;EACR,SAAS;EACT,SAAS,CAAC;GAAE,SAAS;GAA4C;EAAO,CAAC;CAC3E,EACF;AACF;AAMA,SAAgB,MAAuC,QAAW,MAA0B;CAC1F,MAAM,SAAS,OAAO,UAAU,IAAI;CACpC,IAAI,OAAO,SACT,OAAO;EACL,OAAO;EACP,MAAM,OAAO;CACf;CAmBF,OAAO;EAAE,OAAA,EARP,OAAO;GACL,MAAM;GACN,QAAQ;GACR,SAAS;GACT,SAAS,CAAC;IAAE,SAAS;IAA6C,iBAZ9C,OAAO,MAAM,OAAO,KAAK,EAAE,MAAM,MAAM,eAAe;KAC5E,OAAO,KAAK,KAAK,GAAG;KACpB,aAAa;KACb,QAAQ,KAAK,YAAY;KACzB,kBAAkB;MAAE,QAAQ;MAAkB;KAAQ;IACxD,EAOoF;GAAE,CAAC;EACrF,EAGW;EAAG,MAAM;CAAK;AAC7B;AAEA,eAAsB,qBAAqB,QAAgB,OAAe;CAQxE,KAAI,OADgB,MANG,MAAM,6DAA6D;EACxF,QAAQ;EACR,SAAS,EAAE,gBAAgB,oCAAoC;EAC/D,MAAM,IAAI,gBAAgB;GAAE;GAAQ,UAAU;EAAM,CAAC;CACvD,CAAC,EAAA,CAE4B,KAAK,EAAA,CACzB,SAAS,OAAO,EAAE,OAAO,KAAK;CACvC,OAAO,EAAE,OAAO,gBAAgB,+BAA+B,EAAE;AACnE"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@shware/security",
|
|
3
|
-
"version": "3.0.
|
|
3
|
+
"version": "3.0.1",
|
|
4
4
|
"private": false,
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -42,7 +42,7 @@
|
|
|
42
42
|
"path-to-regexp": "^8.4.2",
|
|
43
43
|
"uuid": "^14.0.1",
|
|
44
44
|
"zod": "^4.4.3",
|
|
45
|
-
"@shware/utils": "^1.5.
|
|
45
|
+
"@shware/utils": "^1.5.2"
|
|
46
46
|
},
|
|
47
47
|
"devDependencies": {
|
|
48
48
|
"@types/node": "^26.1.1",
|