@shware/security 3.1.0 → 3.2.0
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 +14 -10
- package/dist/auth/index.cjs.map +1 -1
- package/dist/auth/index.mjs +14 -10
- package/dist/auth/index.mjs.map +1 -1
- package/dist/email/schema.cjs.map +1 -1
- package/dist/oauth2/client.cjs.map +1 -1
- package/dist/oauth2/provider/apple-client-secret.cjs +46 -0
- package/dist/oauth2/provider/apple-client-secret.cjs.map +1 -0
- package/dist/oauth2/provider/apple-client-secret.d.cts +28 -0
- package/dist/oauth2/provider/apple-client-secret.d.cts.map +1 -0
- package/dist/oauth2/provider/apple-client-secret.d.mts +28 -0
- package/dist/oauth2/provider/apple-client-secret.d.mts.map +1 -0
- package/dist/oauth2/provider/apple-client-secret.mjs +45 -0
- package/dist/oauth2/provider/apple-client-secret.mjs.map +1 -0
- package/dist/oauth2/provider/common.cjs +2 -1
- package/dist/oauth2/provider/common.cjs.map +1 -1
- package/dist/oauth2/provider/common.mjs +2 -1
- package/dist/oauth2/provider/common.mjs.map +1 -1
- package/dist/oauth2/provider/index.cjs +2 -0
- package/dist/oauth2/provider/index.d.cts +2 -1
- package/dist/oauth2/provider/index.d.mts +2 -1
- package/dist/oauth2/provider/index.mjs +2 -1
- package/dist/session/db.cjs.map +1 -1
- package/dist/session/map-session.cjs +1 -1
- package/dist/session/map-session.cjs.map +1 -1
- package/dist/session/map-session.mjs +1 -1
- package/dist/session/map-session.mjs.map +1 -1
- package/dist/session/redis.cjs +1 -1
- package/dist/session/redis.cjs.map +1 -1
- package/dist/session/redis.mjs +1 -1
- package/dist/session/redis.mjs.map +1 -1
- package/dist/utils/http.cjs.map +1 -1
- package/dist/utils/timing.cjs +1 -1
- package/dist/utils/timing.cjs.map +1 -1
- package/dist/utils/timing.mjs +1 -1
- package/dist/utils/timing.mjs.map +1 -1
- package/dist/utils/valid.cjs.map +1 -1
- package/dist/utils/valid.mjs.map +1 -1
- package/package.json +8 -8
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
//#region src/oauth2/provider/apple-client-secret.d.ts
|
|
2
|
+
interface AppleClientSecretOptions {
|
|
3
|
+
/** Apple Developer Team ID (Membership details). */
|
|
4
|
+
teamId: string;
|
|
5
|
+
/** Key ID of a key with Sign in with Apple enabled (Certificates, Identifiers & Profiles → Keys). */
|
|
6
|
+
keyId: string;
|
|
7
|
+
/** Contents of that key's `.p8` file: a PKCS#8 PEM. */
|
|
8
|
+
privateKey: string;
|
|
9
|
+
/** Lifetime of each signed secret, in seconds. Apple caps it at six months. Default: one hour. */
|
|
10
|
+
expiresIn?: number;
|
|
11
|
+
/** Re-sign once fewer than this many seconds remain, so a cached secret never reaches Apple expired. Default: five minutes. */
|
|
12
|
+
renewBefore?: number;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Sign in with Apple has no static client secret: the secret is a JWT the server signs with its
|
|
16
|
+
* Sign in with Apple key (ES256, `iss` = team, `sub` = client id, `aud` = appleid.apple.com), and
|
|
17
|
+
* a team signs one per client id — the app's bundle id and the web Services ID share the key and
|
|
18
|
+
* differ only in `sub`.
|
|
19
|
+
*
|
|
20
|
+
* Returns `clientId => secret`, signing on demand and caching per client id until `renewBefore`
|
|
21
|
+
* seconds before expiry, so the secret can be minted by the server at runtime (an
|
|
22
|
+
* `OAuth2ClientConfig.registration` function) instead of being generated by hand and stored, and
|
|
23
|
+
* rotated, as a static secret.
|
|
24
|
+
*/
|
|
25
|
+
declare function createAppleClientSecret(options: AppleClientSecretOptions): (clientId: string) => Promise<string>;
|
|
26
|
+
//#endregion
|
|
27
|
+
export { AppleClientSecretOptions, createAppleClientSecret };
|
|
28
|
+
//# sourceMappingURL=apple-client-secret.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"apple-client-secret.d.cts","names":[],"sources":["../../../src/oauth2/provider/apple-client-secret.ts"],"mappings":";UAEiB;;EAEf;;EAEA;;EAEA;;EAEA;;EAEA;;;;;;;;;;;;;iBAcc,wBAAwB,SAAS,4BAAwB,qBAmBZ"}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
//#region src/oauth2/provider/apple-client-secret.d.ts
|
|
2
|
+
interface AppleClientSecretOptions {
|
|
3
|
+
/** Apple Developer Team ID (Membership details). */
|
|
4
|
+
teamId: string;
|
|
5
|
+
/** Key ID of a key with Sign in with Apple enabled (Certificates, Identifiers & Profiles → Keys). */
|
|
6
|
+
keyId: string;
|
|
7
|
+
/** Contents of that key's `.p8` file: a PKCS#8 PEM. */
|
|
8
|
+
privateKey: string;
|
|
9
|
+
/** Lifetime of each signed secret, in seconds. Apple caps it at six months. Default: one hour. */
|
|
10
|
+
expiresIn?: number;
|
|
11
|
+
/** Re-sign once fewer than this many seconds remain, so a cached secret never reaches Apple expired. Default: five minutes. */
|
|
12
|
+
renewBefore?: number;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Sign in with Apple has no static client secret: the secret is a JWT the server signs with its
|
|
16
|
+
* Sign in with Apple key (ES256, `iss` = team, `sub` = client id, `aud` = appleid.apple.com), and
|
|
17
|
+
* a team signs one per client id — the app's bundle id and the web Services ID share the key and
|
|
18
|
+
* differ only in `sub`.
|
|
19
|
+
*
|
|
20
|
+
* Returns `clientId => secret`, signing on demand and caching per client id until `renewBefore`
|
|
21
|
+
* seconds before expiry, so the secret can be minted by the server at runtime (an
|
|
22
|
+
* `OAuth2ClientConfig.registration` function) instead of being generated by hand and stored, and
|
|
23
|
+
* rotated, as a static secret.
|
|
24
|
+
*/
|
|
25
|
+
declare function createAppleClientSecret(options: AppleClientSecretOptions): (clientId: string) => Promise<string>;
|
|
26
|
+
//#endregion
|
|
27
|
+
export { AppleClientSecretOptions, createAppleClientSecret };
|
|
28
|
+
//# sourceMappingURL=apple-client-secret.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"apple-client-secret.d.mts","names":[],"sources":["../../../src/oauth2/provider/apple-client-secret.ts"],"mappings":";UAEiB;;EAEf;;EAEA;;EAEA;;EAEA;;EAEA;;;;;;;;;;;;;iBAcc,wBAAwB,SAAS,4BAAwB,qBAmBZ"}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { SignJWT, importPKCS8 } from "jose";
|
|
2
|
+
//#region src/oauth2/provider/apple-client-secret.ts
|
|
3
|
+
/**
|
|
4
|
+
* Sign in with Apple has no static client secret: the secret is a JWT the server signs with its
|
|
5
|
+
* Sign in with Apple key (ES256, `iss` = team, `sub` = client id, `aud` = appleid.apple.com), and
|
|
6
|
+
* a team signs one per client id — the app's bundle id and the web Services ID share the key and
|
|
7
|
+
* differ only in `sub`.
|
|
8
|
+
*
|
|
9
|
+
* Returns `clientId => secret`, signing on demand and caching per client id until `renewBefore`
|
|
10
|
+
* seconds before expiry, so the secret can be minted by the server at runtime (an
|
|
11
|
+
* `OAuth2ClientConfig.registration` function) instead of being generated by hand and stored, and
|
|
12
|
+
* rotated, as a static secret.
|
|
13
|
+
*/
|
|
14
|
+
function createAppleClientSecret(options) {
|
|
15
|
+
const { teamId, keyId, privateKey, expiresIn = 3600, renewBefore = 300 } = options;
|
|
16
|
+
if (renewBefore >= expiresIn) throw new Error("renewBefore must be shorter than expiresIn");
|
|
17
|
+
let key;
|
|
18
|
+
const cache = /* @__PURE__ */ new Map();
|
|
19
|
+
function getKey() {
|
|
20
|
+
key ??= importPKCS8(privateKey, "ES256").catch((error) => {
|
|
21
|
+
key = void 0;
|
|
22
|
+
throw error;
|
|
23
|
+
});
|
|
24
|
+
return key;
|
|
25
|
+
}
|
|
26
|
+
return async function appleClientSecret(clientId) {
|
|
27
|
+
const now = Math.floor(Date.now() / 1e3);
|
|
28
|
+
const cached = cache.get(clientId);
|
|
29
|
+
if (cached && cached.exp - now > renewBefore) return cached.secret;
|
|
30
|
+
const exp = now + expiresIn;
|
|
31
|
+
const secret = await new SignJWT({}).setProtectedHeader({
|
|
32
|
+
alg: "ES256",
|
|
33
|
+
kid: keyId
|
|
34
|
+
}).setIssuer(teamId).setSubject(clientId).setAudience("https://appleid.apple.com").setIssuedAt(now).setExpirationTime(exp).sign(await getKey());
|
|
35
|
+
cache.set(clientId, {
|
|
36
|
+
secret,
|
|
37
|
+
exp
|
|
38
|
+
});
|
|
39
|
+
return secret;
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
//#endregion
|
|
43
|
+
export { createAppleClientSecret };
|
|
44
|
+
|
|
45
|
+
//# sourceMappingURL=apple-client-secret.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"apple-client-secret.mjs","names":[],"sources":["../../../src/oauth2/provider/apple-client-secret.ts"],"sourcesContent":["import { SignJWT, importPKCS8 } from 'jose';\n\nexport interface AppleClientSecretOptions {\n /** Apple Developer Team ID (Membership details). */\n teamId: string;\n /** Key ID of a key with Sign in with Apple enabled (Certificates, Identifiers & Profiles → Keys). */\n keyId: string;\n /** Contents of that key's `.p8` file: a PKCS#8 PEM. */\n privateKey: string;\n /** Lifetime of each signed secret, in seconds. Apple caps it at six months. Default: one hour. */\n expiresIn?: number;\n /** Re-sign once fewer than this many seconds remain, so a cached secret never reaches Apple expired. Default: five minutes. */\n renewBefore?: number;\n}\n\n/**\n * Sign in with Apple has no static client secret: the secret is a JWT the server signs with its\n * Sign in with Apple key (ES256, `iss` = team, `sub` = client id, `aud` = appleid.apple.com), and\n * a team signs one per client id — the app's bundle id and the web Services ID share the key and\n * differ only in `sub`.\n *\n * Returns `clientId => secret`, signing on demand and caching per client id until `renewBefore`\n * seconds before expiry, so the secret can be minted by the server at runtime (an\n * `OAuth2ClientConfig.registration` function) instead of being generated by hand and stored, and\n * rotated, as a static secret.\n */\nexport function createAppleClientSecret(options: AppleClientSecretOptions) {\n const { teamId, keyId, privateKey, expiresIn = 3600, renewBefore = 300 } = options;\n if (renewBefore >= expiresIn) {\n throw new Error('renewBefore must be shorter than expiresIn');\n }\n\n // The import is cached as a promise so concurrent first calls share one; a failed import is\n // dropped so the next call retries instead of failing forever.\n let key: Promise<CryptoKey> | undefined;\n const cache = new Map<string, { secret: string; exp: number }>();\n\n function getKey() {\n key ??= importPKCS8(privateKey, 'ES256').catch((error: unknown) => {\n key = undefined;\n throw error;\n });\n return key;\n }\n\n return async function appleClientSecret(clientId: string): Promise<string> {\n const now = Math.floor(Date.now() / 1000);\n const cached = cache.get(clientId);\n if (cached && cached.exp - now > renewBefore) return cached.secret;\n\n const exp = now + expiresIn;\n const secret = await new SignJWT({})\n .setProtectedHeader({ alg: 'ES256', kid: keyId })\n .setIssuer(teamId)\n .setSubject(clientId)\n .setAudience('https://appleid.apple.com')\n .setIssuedAt(now)\n .setExpirationTime(exp)\n .sign(await getKey());\n cache.set(clientId, { secret, exp });\n return secret;\n };\n}\n"],"mappings":";;;;;;;;;;;;;AA0BA,SAAgB,wBAAwB,SAAmC;CACzE,MAAM,EAAE,QAAQ,OAAO,YAAY,YAAY,MAAM,cAAc,QAAQ;CAC3E,IAAI,eAAe,WACjB,MAAM,IAAI,MAAM,4CAA4C;CAK9D,IAAI;CACJ,MAAM,wBAAQ,IAAI,IAA6C;CAE/D,SAAS,SAAS;EAChB,QAAQ,YAAY,YAAY,OAAO,CAAC,CAAC,OAAO,UAAmB;GACjE,MAAM,KAAA;GACN,MAAM;EACR,CAAC;EACD,OAAO;CACT;CAEA,OAAO,eAAe,kBAAkB,UAAmC;EACzE,MAAM,MAAM,KAAK,MAAM,KAAK,IAAI,IAAI,GAAI;EACxC,MAAM,SAAS,MAAM,IAAI,QAAQ;EACjC,IAAI,UAAU,OAAO,MAAM,MAAM,aAAa,OAAO,OAAO;EAE5D,MAAM,MAAM,MAAM;EAClB,MAAM,SAAS,MAAM,IAAI,QAAQ,CAAC,CAAC,CAAC,CACjC,mBAAmB;GAAE,KAAK;GAAS,KAAK;EAAM,CAAC,CAAC,CAChD,UAAU,MAAM,CAAC,CACjB,WAAW,QAAQ,CAAC,CACpB,YAAY,2BAA2B,CAAC,CACxC,YAAY,GAAG,CAAC,CAChB,kBAAkB,GAAG,CAAC,CACtB,KAAK,MAAM,OAAO,CAAC;EACtB,MAAM,IAAI,UAAU;GAAE;GAAQ;EAAI,CAAC;EACnC,OAAO;CACT;AACF"}
|
|
@@ -80,7 +80,8 @@ async function revokeToken(params) {
|
|
|
80
80
|
}
|
|
81
81
|
async function verifyIdToken(idToken, jwkSetUri) {
|
|
82
82
|
try {
|
|
83
|
-
const
|
|
83
|
+
const jwks = (0, jose.createRemoteJWKSet)(new URL(jwkSetUri));
|
|
84
|
+
const { payload } = await (0, jose.jwtVerify)(idToken, jwks);
|
|
84
85
|
return payload;
|
|
85
86
|
} catch {
|
|
86
87
|
console.error("Failed to verify id_token");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"common.cjs","names":["OAuth2Error"],"sources":["../../../src/oauth2/provider/common.ts"],"sourcesContent":["import { createRemoteJWKSet, jwtVerify } from 'jose';\nimport { OAuth2Error } from '../error';\nimport type { ExchangeCodeParams, PkceParameters, RefreshTokenParams } from '../types';\n\nexport function createAuthorizationUri(options: {\n state: string;\n scope: string[];\n clientId: string;\n redirectUri: string;\n authorizationUri: string;\n pkce?: Omit<PkceParameters, 'code_verifier'>;\n}) {\n const url = new URL(options.authorizationUri);\n url.searchParams.append('response_type', 'code');\n url.searchParams.append('client_id', options.clientId);\n url.searchParams.append('state', options.state);\n url.searchParams.append('scope', options.scope.join(' '));\n url.searchParams.append('redirect_uri', options.redirectUri);\n if (options.pkce) {\n url.searchParams.append('code_challenge_method', options.pkce.code_challenge_method);\n url.searchParams.append('code_challenge', options.pkce.code_challenge);\n }\n return url;\n}\n\nexport async function exchangeAuthorizationCode(\n params: ExchangeCodeParams & {\n tokenUri: string;\n authentication?: 'basic' | 'post';\n }\n) {\n const body = new URLSearchParams();\n body.append('code', params.code);\n body.append('redirect_uri', params.redirectUri);\n body.append('grant_type', 'authorization_code');\n if (params.pkce) body.append('code_verifier', params.pkce.code_verifier);\n\n const headers: Record<string, string> = {\n Accept: 'application/json',\n 'Content-Type': 'application/x-www-form-urlencoded',\n };\n if (params.authentication === 'basic') {\n const token = Buffer.from(`${params.clientId}:${params.clientSecret}`).toString('base64');\n headers.Authorization = `Basic ${token}`;\n } else {\n body.append('client_id', params.clientId);\n body.append('client_secret', params.clientSecret);\n }\n\n return fetch(params.tokenUri, { method: 'POST', headers, body });\n}\n\nexport async function refreshAccessToken(\n params: RefreshTokenParams & {\n tokenUri: string;\n authentication?: 'basic' | 'post';\n }\n) {\n const body = new URLSearchParams();\n body.append('grant_type', 'refresh_token');\n body.append('refresh_token', params.refreshToken);\n\n const headers: Record<string, string> = {\n Accept: 'application/json',\n 'Content-Type': 'application/x-www-form-urlencoded',\n };\n\n if (params.authentication === 'basic') {\n const token = Buffer.from(`${params.clientId}:${params.clientSecret}`).toString('base64');\n headers.Authorization = `Basic ${token}`;\n } else {\n body.append('client_id', params.clientId);\n body.append('client_secret', params.clientSecret);\n }\n\n return fetch(params.tokenUri, { method: 'POST', headers, body });\n}\n\ninterface RevokeTokenParams {\n token: string;\n clientId: string;\n clientSecret: string;\n tokenRevokeUri: string;\n authentication?: 'basic' | 'post';\n}\n\nexport async function revokeToken(params: RevokeTokenParams) {\n const body = new URLSearchParams();\n body.append('token', params.token);\n const headers: Record<string, string> = {\n Accept: 'application/json',\n 'Content-Type': 'application/x-www-form-urlencoded',\n };\n\n if (params.authentication === 'basic') {\n const token = Buffer.from(`${params.clientId}:${params.clientSecret}`).toString('base64');\n headers.Authorization = `Basic ${token}`;\n } else {\n body.append('client_id', params.clientId);\n body.append('client_secret', params.clientSecret);\n }\n\n const response = await fetch(params.tokenRevokeUri, { method: 'POST', headers, body });\n if (!response.ok) {\n const error = await response.json();\n console.error('Refresh token error:', error);\n throw new OAuth2Error(response.status, 'invalid_request', 'Failed to revoke token');\n }\n}\n\nexport async function verifyIdToken<T>(idToken: string, jwkSetUri: string) {\n try {\n const jwks = createRemoteJWKSet(new URL(jwkSetUri));\n const { payload } = await jwtVerify(idToken, jwks);\n return payload as T;\n } catch {\n console.error('Failed to verify id_token');\n throw new OAuth2Error(400, 'invalid_request', 'Failed to verify id_token');\n }\n}\n"],"mappings":";;;;AAIA,SAAgB,uBAAuB,SAOpC;CACD,MAAM,MAAM,IAAI,IAAI,QAAQ,gBAAgB;CAC5C,IAAI,aAAa,OAAO,iBAAiB,MAAM;CAC/C,IAAI,aAAa,OAAO,aAAa,QAAQ,QAAQ;CACrD,IAAI,aAAa,OAAO,SAAS,QAAQ,KAAK;CAC9C,IAAI,aAAa,OAAO,SAAS,QAAQ,MAAM,KAAK,GAAG,CAAC;CACxD,IAAI,aAAa,OAAO,gBAAgB,QAAQ,WAAW;CAC3D,IAAI,QAAQ,MAAM;EAChB,IAAI,aAAa,OAAO,yBAAyB,QAAQ,KAAK,qBAAqB;EACnF,IAAI,aAAa,OAAO,kBAAkB,QAAQ,KAAK,cAAc;CACvE;CACA,OAAO;AACT;AAEA,eAAsB,0BACpB,QAIA;CACA,MAAM,OAAO,IAAI,gBAAgB;CACjC,KAAK,OAAO,QAAQ,OAAO,IAAI;CAC/B,KAAK,OAAO,gBAAgB,OAAO,WAAW;CAC9C,KAAK,OAAO,cAAc,oBAAoB;CAC9C,IAAI,OAAO,MAAM,KAAK,OAAO,iBAAiB,OAAO,KAAK,aAAa;CAEvE,MAAM,UAAkC;EACtC,QAAQ;EACR,gBAAgB;CAClB;CACA,IAAI,OAAO,mBAAmB,SAE5B,QAAQ,gBAAgB,SADV,OAAO,KAAK,GAAG,OAAO,SAAS,GAAG,OAAO,cAAc,CAAC,CAAC,SAAS,QAC3C;MAChC;EACL,KAAK,OAAO,aAAa,OAAO,QAAQ;EACxC,KAAK,OAAO,iBAAiB,OAAO,YAAY;CAClD;CAEA,OAAO,MAAM,OAAO,UAAU;EAAE,QAAQ;EAAQ;EAAS;CAAK,CAAC;AACjE;AAEA,eAAsB,mBACpB,QAIA;CACA,MAAM,OAAO,IAAI,gBAAgB;CACjC,KAAK,OAAO,cAAc,eAAe;CACzC,KAAK,OAAO,iBAAiB,OAAO,YAAY;CAEhD,MAAM,UAAkC;EACtC,QAAQ;EACR,gBAAgB;CAClB;CAEA,IAAI,OAAO,mBAAmB,SAE5B,QAAQ,gBAAgB,SADV,OAAO,KAAK,GAAG,OAAO,SAAS,GAAG,OAAO,cAAc,CAAC,CAAC,SAAS,QAC3C;MAChC;EACL,KAAK,OAAO,aAAa,OAAO,QAAQ;EACxC,KAAK,OAAO,iBAAiB,OAAO,YAAY;CAClD;CAEA,OAAO,MAAM,OAAO,UAAU;EAAE,QAAQ;EAAQ;EAAS;CAAK,CAAC;AACjE;AAUA,eAAsB,YAAY,QAA2B;CAC3D,MAAM,OAAO,IAAI,gBAAgB;CACjC,KAAK,OAAO,SAAS,OAAO,KAAK;CACjC,MAAM,UAAkC;EACtC,QAAQ;EACR,gBAAgB;CAClB;CAEA,IAAI,OAAO,mBAAmB,SAE5B,QAAQ,gBAAgB,SADV,OAAO,KAAK,GAAG,OAAO,SAAS,GAAG,OAAO,cAAc,CAAC,CAAC,SAAS,QAC3C;MAChC;EACL,KAAK,OAAO,aAAa,OAAO,QAAQ;EACxC,KAAK,OAAO,iBAAiB,OAAO,YAAY;CAClD;CAEA,MAAM,WAAW,MAAM,MAAM,OAAO,gBAAgB;EAAE,QAAQ;EAAQ;EAAS;CAAK,CAAC;CACrF,IAAI,CAAC,SAAS,IAAI;EAChB,MAAM,QAAQ,MAAM,SAAS,KAAK;EAClC,QAAQ,MAAM,wBAAwB,KAAK;EAC3C,MAAM,IAAIA,qBAAAA,YAAY,SAAS,QAAQ,mBAAmB,wBAAwB;CACpF;AACF;AAEA,eAAsB,cAAiB,SAAiB,WAAmB;CACzE,IAAI;
|
|
1
|
+
{"version":3,"file":"common.cjs","names":["OAuth2Error","createRemoteJWKSet","jwtVerify"],"sources":["../../../src/oauth2/provider/common.ts"],"sourcesContent":["import { createRemoteJWKSet, jwtVerify } from 'jose';\nimport { OAuth2Error } from '../error';\nimport type { ExchangeCodeParams, PkceParameters, RefreshTokenParams } from '../types';\n\nexport function createAuthorizationUri(options: {\n state: string;\n scope: string[];\n clientId: string;\n redirectUri: string;\n authorizationUri: string;\n pkce?: Omit<PkceParameters, 'code_verifier'>;\n}) {\n const url = new URL(options.authorizationUri);\n url.searchParams.append('response_type', 'code');\n url.searchParams.append('client_id', options.clientId);\n url.searchParams.append('state', options.state);\n url.searchParams.append('scope', options.scope.join(' '));\n url.searchParams.append('redirect_uri', options.redirectUri);\n if (options.pkce) {\n url.searchParams.append('code_challenge_method', options.pkce.code_challenge_method);\n url.searchParams.append('code_challenge', options.pkce.code_challenge);\n }\n return url;\n}\n\nexport async function exchangeAuthorizationCode(\n params: ExchangeCodeParams & {\n tokenUri: string;\n authentication?: 'basic' | 'post';\n }\n) {\n const body = new URLSearchParams();\n body.append('code', params.code);\n body.append('redirect_uri', params.redirectUri);\n body.append('grant_type', 'authorization_code');\n if (params.pkce) body.append('code_verifier', params.pkce.code_verifier);\n\n const headers: Record<string, string> = {\n Accept: 'application/json',\n 'Content-Type': 'application/x-www-form-urlencoded',\n };\n if (params.authentication === 'basic') {\n const token = Buffer.from(`${params.clientId}:${params.clientSecret}`).toString('base64');\n headers.Authorization = `Basic ${token}`;\n } else {\n body.append('client_id', params.clientId);\n body.append('client_secret', params.clientSecret);\n }\n\n return fetch(params.tokenUri, { method: 'POST', headers, body });\n}\n\nexport async function refreshAccessToken(\n params: RefreshTokenParams & {\n tokenUri: string;\n authentication?: 'basic' | 'post';\n }\n) {\n const body = new URLSearchParams();\n body.append('grant_type', 'refresh_token');\n body.append('refresh_token', params.refreshToken);\n\n const headers: Record<string, string> = {\n Accept: 'application/json',\n 'Content-Type': 'application/x-www-form-urlencoded',\n };\n\n if (params.authentication === 'basic') {\n const token = Buffer.from(`${params.clientId}:${params.clientSecret}`).toString('base64');\n headers.Authorization = `Basic ${token}`;\n } else {\n body.append('client_id', params.clientId);\n body.append('client_secret', params.clientSecret);\n }\n\n return fetch(params.tokenUri, { method: 'POST', headers, body });\n}\n\ninterface RevokeTokenParams {\n token: string;\n clientId: string;\n clientSecret: string;\n tokenRevokeUri: string;\n authentication?: 'basic' | 'post';\n}\n\nexport async function revokeToken(params: RevokeTokenParams) {\n const body = new URLSearchParams();\n body.append('token', params.token);\n const headers: Record<string, string> = {\n Accept: 'application/json',\n 'Content-Type': 'application/x-www-form-urlencoded',\n };\n\n if (params.authentication === 'basic') {\n const token = Buffer.from(`${params.clientId}:${params.clientSecret}`).toString('base64');\n headers.Authorization = `Basic ${token}`;\n } else {\n body.append('client_id', params.clientId);\n body.append('client_secret', params.clientSecret);\n }\n\n const response = await fetch(params.tokenRevokeUri, { method: 'POST', headers, body });\n if (!response.ok) {\n const error = await response.json();\n console.error('Refresh token error:', error);\n throw new OAuth2Error(response.status, 'invalid_request', 'Failed to revoke token');\n }\n}\n\nexport async function verifyIdToken<T>(idToken: string, jwkSetUri: string) {\n try {\n const jwks = createRemoteJWKSet(new URL(jwkSetUri));\n const { payload } = await jwtVerify(idToken, jwks);\n return payload as T;\n } catch {\n console.error('Failed to verify id_token');\n throw new OAuth2Error(400, 'invalid_request', 'Failed to verify id_token');\n }\n}\n"],"mappings":";;;;AAIA,SAAgB,uBAAuB,SAOpC;CACD,MAAM,MAAM,IAAI,IAAI,QAAQ,gBAAgB;CAC5C,IAAI,aAAa,OAAO,iBAAiB,MAAM;CAC/C,IAAI,aAAa,OAAO,aAAa,QAAQ,QAAQ;CACrD,IAAI,aAAa,OAAO,SAAS,QAAQ,KAAK;CAC9C,IAAI,aAAa,OAAO,SAAS,QAAQ,MAAM,KAAK,GAAG,CAAC;CACxD,IAAI,aAAa,OAAO,gBAAgB,QAAQ,WAAW;CAC3D,IAAI,QAAQ,MAAM;EAChB,IAAI,aAAa,OAAO,yBAAyB,QAAQ,KAAK,qBAAqB;EACnF,IAAI,aAAa,OAAO,kBAAkB,QAAQ,KAAK,cAAc;CACvE;CACA,OAAO;AACT;AAE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B,SADV,OAAO,KAAK,GAAG,OAAO,SAAS,GAAG,OAAO,cAAc,CAAC,CAAC,SAAS,QAC3C;MAChC;EACL,KAAK,OAAO,aAAa,OAAO,QAAQ;EACxC,KAAK,OAAO,iBAAiB,OAAO,YAAY;CAClD;CAEA,MAAM,WAAW,MAAM,MAAM,OAAO,gBAAgB;EAAE,QAAQ;EAAQ;EAAS;CAAK,CAAC;CACrF,IAAI,CAAC,SAAS,IAAI;EAChB,MAAM,QAAQ,MAAM,SAAS,KAAK;EAClC,QAAQ,MAAM,wBAAwB,KAAK;EAC3C,MAAM,IAAIA,qBAAAA,YAAY,SAAS,QAAQ,mBAAmB,wBAAwB;CACpF;AACF;AAEA,eAAsB,cAAiB,SAAiB,WAAmB;CACzE,IAAI;EACF,MAAM,QAAA,GAAOC,KAAAA,mBAAAA,CAAmB,IAAI,IAAI,SAAS,CAAC;EAClD,MAAM,EAAE,YAAY,OAAA,GAAMC,KAAAA,UAAAA,CAAU,SAAS,IAAI;EACjD,OAAO;CACT,QAAQ;EACN,QAAQ,MAAM,2BAA2B;EACzC,MAAM,IAAIF,qBAAAA,YAAY,KAAK,mBAAmB,2BAA2B;CAC3E;AACF"}
|
|
@@ -79,7 +79,8 @@ async function revokeToken(params) {
|
|
|
79
79
|
}
|
|
80
80
|
async function verifyIdToken(idToken, jwkSetUri) {
|
|
81
81
|
try {
|
|
82
|
-
const
|
|
82
|
+
const jwks = createRemoteJWKSet(new URL(jwkSetUri));
|
|
83
|
+
const { payload } = await jwtVerify(idToken, jwks);
|
|
83
84
|
return payload;
|
|
84
85
|
} catch {
|
|
85
86
|
console.error("Failed to verify id_token");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"common.mjs","names":[],"sources":["../../../src/oauth2/provider/common.ts"],"sourcesContent":["import { createRemoteJWKSet, jwtVerify } from 'jose';\nimport { OAuth2Error } from '../error';\nimport type { ExchangeCodeParams, PkceParameters, RefreshTokenParams } from '../types';\n\nexport function createAuthorizationUri(options: {\n state: string;\n scope: string[];\n clientId: string;\n redirectUri: string;\n authorizationUri: string;\n pkce?: Omit<PkceParameters, 'code_verifier'>;\n}) {\n const url = new URL(options.authorizationUri);\n url.searchParams.append('response_type', 'code');\n url.searchParams.append('client_id', options.clientId);\n url.searchParams.append('state', options.state);\n url.searchParams.append('scope', options.scope.join(' '));\n url.searchParams.append('redirect_uri', options.redirectUri);\n if (options.pkce) {\n url.searchParams.append('code_challenge_method', options.pkce.code_challenge_method);\n url.searchParams.append('code_challenge', options.pkce.code_challenge);\n }\n return url;\n}\n\nexport async function exchangeAuthorizationCode(\n params: ExchangeCodeParams & {\n tokenUri: string;\n authentication?: 'basic' | 'post';\n }\n) {\n const body = new URLSearchParams();\n body.append('code', params.code);\n body.append('redirect_uri', params.redirectUri);\n body.append('grant_type', 'authorization_code');\n if (params.pkce) body.append('code_verifier', params.pkce.code_verifier);\n\n const headers: Record<string, string> = {\n Accept: 'application/json',\n 'Content-Type': 'application/x-www-form-urlencoded',\n };\n if (params.authentication === 'basic') {\n const token = Buffer.from(`${params.clientId}:${params.clientSecret}`).toString('base64');\n headers.Authorization = `Basic ${token}`;\n } else {\n body.append('client_id', params.clientId);\n body.append('client_secret', params.clientSecret);\n }\n\n return fetch(params.tokenUri, { method: 'POST', headers, body });\n}\n\nexport async function refreshAccessToken(\n params: RefreshTokenParams & {\n tokenUri: string;\n authentication?: 'basic' | 'post';\n }\n) {\n const body = new URLSearchParams();\n body.append('grant_type', 'refresh_token');\n body.append('refresh_token', params.refreshToken);\n\n const headers: Record<string, string> = {\n Accept: 'application/json',\n 'Content-Type': 'application/x-www-form-urlencoded',\n };\n\n if (params.authentication === 'basic') {\n const token = Buffer.from(`${params.clientId}:${params.clientSecret}`).toString('base64');\n headers.Authorization = `Basic ${token}`;\n } else {\n body.append('client_id', params.clientId);\n body.append('client_secret', params.clientSecret);\n }\n\n return fetch(params.tokenUri, { method: 'POST', headers, body });\n}\n\ninterface RevokeTokenParams {\n token: string;\n clientId: string;\n clientSecret: string;\n tokenRevokeUri: string;\n authentication?: 'basic' | 'post';\n}\n\nexport async function revokeToken(params: RevokeTokenParams) {\n const body = new URLSearchParams();\n body.append('token', params.token);\n const headers: Record<string, string> = {\n Accept: 'application/json',\n 'Content-Type': 'application/x-www-form-urlencoded',\n };\n\n if (params.authentication === 'basic') {\n const token = Buffer.from(`${params.clientId}:${params.clientSecret}`).toString('base64');\n headers.Authorization = `Basic ${token}`;\n } else {\n body.append('client_id', params.clientId);\n body.append('client_secret', params.clientSecret);\n }\n\n const response = await fetch(params.tokenRevokeUri, { method: 'POST', headers, body });\n if (!response.ok) {\n const error = await response.json();\n console.error('Refresh token error:', error);\n throw new OAuth2Error(response.status, 'invalid_request', 'Failed to revoke token');\n }\n}\n\nexport async function verifyIdToken<T>(idToken: string, jwkSetUri: string) {\n try {\n const jwks = createRemoteJWKSet(new URL(jwkSetUri));\n const { payload } = await jwtVerify(idToken, jwks);\n return payload as T;\n } catch {\n console.error('Failed to verify id_token');\n throw new OAuth2Error(400, 'invalid_request', 'Failed to verify id_token');\n }\n}\n"],"mappings":";;;AAIA,SAAgB,uBAAuB,SAOpC;CACD,MAAM,MAAM,IAAI,IAAI,QAAQ,gBAAgB;CAC5C,IAAI,aAAa,OAAO,iBAAiB,MAAM;CAC/C,IAAI,aAAa,OAAO,aAAa,QAAQ,QAAQ;CACrD,IAAI,aAAa,OAAO,SAAS,QAAQ,KAAK;CAC9C,IAAI,aAAa,OAAO,SAAS,QAAQ,MAAM,KAAK,GAAG,CAAC;CACxD,IAAI,aAAa,OAAO,gBAAgB,QAAQ,WAAW;CAC3D,IAAI,QAAQ,MAAM;EAChB,IAAI,aAAa,OAAO,yBAAyB,QAAQ,KAAK,qBAAqB;EACnF,IAAI,aAAa,OAAO,kBAAkB,QAAQ,KAAK,cAAc;CACvE;CACA,OAAO;AACT;AAEA,eAAsB,0BACpB,QAIA;CACA,MAAM,OAAO,IAAI,gBAAgB;CACjC,KAAK,OAAO,QAAQ,OA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AChC;EACL,KAAK,OAAO,aAAa,OAAO,QAAQ;EACxC,KAAK,OAAO,iBAAiB,OAAO,YAAY;CAClD;CAEA,MAAM,WAAW,MAAM,MAAM,OAAO,gBAAgB;EAAE,QAAQ;EAAQ;EAAS;CAAK,CAAC;CACrF,IAAI,CAAC,SAAS,IAAI;EAChB,MAAM,QAAQ,MAAM,SAAS,KAAK;EAClC,QAAQ,MAAM,wBAAwB,KAAK;EAC3C,MAAM,IAAI,YAAY,SAAS,QAAQ,mBAAmB,wBAAwB;CACpF;AACF;AAEA,eAAsB,cAAiB,SAAiB,WAAmB;CACzE,IAAI;
|
|
1
|
+
{"version":3,"file":"common.mjs","names":[],"sources":["../../../src/oauth2/provider/common.ts"],"sourcesContent":["import { createRemoteJWKSet, jwtVerify } from 'jose';\nimport { OAuth2Error } from '../error';\nimport type { ExchangeCodeParams, PkceParameters, RefreshTokenParams } from '../types';\n\nexport function createAuthorizationUri(options: {\n state: string;\n scope: string[];\n clientId: string;\n redirectUri: string;\n authorizationUri: string;\n pkce?: Omit<PkceParameters, 'code_verifier'>;\n}) {\n const url = new URL(options.authorizationUri);\n url.searchParams.append('response_type', 'code');\n url.searchParams.append('client_id', options.clientId);\n url.searchParams.append('state', options.state);\n url.searchParams.append('scope', options.scope.join(' '));\n url.searchParams.append('redirect_uri', options.redirectUri);\n if (options.pkce) {\n url.searchParams.append('code_challenge_method', options.pkce.code_challenge_method);\n url.searchParams.append('code_challenge', options.pkce.code_challenge);\n }\n return url;\n}\n\nexport async function exchangeAuthorizationCode(\n params: ExchangeCodeParams & {\n tokenUri: string;\n authentication?: 'basic' | 'post';\n }\n) {\n const body = new URLSearchParams();\n body.append('code', params.code);\n body.append('redirect_uri', params.redirectUri);\n body.append('grant_type', 'authorization_code');\n if (params.pkce) body.append('code_verifier', params.pkce.code_verifier);\n\n const headers: Record<string, string> = {\n Accept: 'application/json',\n 'Content-Type': 'application/x-www-form-urlencoded',\n };\n if (params.authentication === 'basic') {\n const token = Buffer.from(`${params.clientId}:${params.clientSecret}`).toString('base64');\n headers.Authorization = `Basic ${token}`;\n } else {\n body.append('client_id', params.clientId);\n body.append('client_secret', params.clientSecret);\n }\n\n return fetch(params.tokenUri, { method: 'POST', headers, body });\n}\n\nexport async function refreshAccessToken(\n params: RefreshTokenParams & {\n tokenUri: string;\n authentication?: 'basic' | 'post';\n }\n) {\n const body = new URLSearchParams();\n body.append('grant_type', 'refresh_token');\n body.append('refresh_token', params.refreshToken);\n\n const headers: Record<string, string> = {\n Accept: 'application/json',\n 'Content-Type': 'application/x-www-form-urlencoded',\n };\n\n if (params.authentication === 'basic') {\n const token = Buffer.from(`${params.clientId}:${params.clientSecret}`).toString('base64');\n headers.Authorization = `Basic ${token}`;\n } else {\n body.append('client_id', params.clientId);\n body.append('client_secret', params.clientSecret);\n }\n\n return fetch(params.tokenUri, { method: 'POST', headers, body });\n}\n\ninterface RevokeTokenParams {\n token: string;\n clientId: string;\n clientSecret: string;\n tokenRevokeUri: string;\n authentication?: 'basic' | 'post';\n}\n\nexport async function revokeToken(params: RevokeTokenParams) {\n const body = new URLSearchParams();\n body.append('token', params.token);\n const headers: Record<string, string> = {\n Accept: 'application/json',\n 'Content-Type': 'application/x-www-form-urlencoded',\n };\n\n if (params.authentication === 'basic') {\n const token = Buffer.from(`${params.clientId}:${params.clientSecret}`).toString('base64');\n headers.Authorization = `Basic ${token}`;\n } else {\n body.append('client_id', params.clientId);\n body.append('client_secret', params.clientSecret);\n }\n\n const response = await fetch(params.tokenRevokeUri, { method: 'POST', headers, body });\n if (!response.ok) {\n const error = await response.json();\n console.error('Refresh token error:', error);\n throw new OAuth2Error(response.status, 'invalid_request', 'Failed to revoke token');\n }\n}\n\nexport async function verifyIdToken<T>(idToken: string, jwkSetUri: string) {\n try {\n const jwks = createRemoteJWKSet(new URL(jwkSetUri));\n const { payload } = await jwtVerify(idToken, jwks);\n return payload as T;\n } catch {\n console.error('Failed to verify id_token');\n throw new OAuth2Error(400, 'invalid_request', 'Failed to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ringTag, { value: "Module" });
|
|
2
2
|
const require_oauth2_provider_apple = require("./apple.cjs");
|
|
3
|
+
const require_oauth2_provider_apple_client_secret = require("./apple-client-secret.cjs");
|
|
3
4
|
const require_oauth2_provider_facebook = require("./facebook.cjs");
|
|
4
5
|
const require_oauth2_provider_github = require("./github.cjs");
|
|
5
6
|
const require_oauth2_provider_google = require("./google.cjs");
|
|
6
7
|
const require_oauth2_provider_wechat = require("./wechat.cjs");
|
|
7
8
|
const require_oauth2_provider_x = require("./x.cjs");
|
|
8
9
|
exports.apple = require_oauth2_provider_apple.apple;
|
|
10
|
+
exports.createAppleClientSecret = require_oauth2_provider_apple_client_secret.createAppleClientSecret;
|
|
9
11
|
exports.facebook = require_oauth2_provider_facebook.facebook;
|
|
10
12
|
exports.github = require_oauth2_provider_github.github;
|
|
11
13
|
exports.google = require_oauth2_provider_google.google;
|
|
@@ -1,7 +1,8 @@
|
|
|
1
|
+
import { AppleClientSecretOptions, createAppleClientSecret } from "./apple-client-secret.cjs";
|
|
1
2
|
import { apple } from "./apple.cjs";
|
|
2
3
|
import { facebook } from "./facebook.cjs";
|
|
3
4
|
import { github } from "./github.cjs";
|
|
4
5
|
import { google } from "./google.cjs";
|
|
5
6
|
import { wechat } from "./wechat.cjs";
|
|
6
7
|
import { x } from "./x.cjs";
|
|
7
|
-
export { apple, facebook, github, google, wechat, x };
|
|
8
|
+
export { type AppleClientSecretOptions, apple, createAppleClientSecret, facebook, github, google, wechat, x };
|
|
@@ -1,7 +1,8 @@
|
|
|
1
|
+
import { AppleClientSecretOptions, createAppleClientSecret } from "./apple-client-secret.mjs";
|
|
1
2
|
import { apple } from "./apple.mjs";
|
|
2
3
|
import { facebook } from "./facebook.mjs";
|
|
3
4
|
import { github } from "./github.mjs";
|
|
4
5
|
import { google } from "./google.mjs";
|
|
5
6
|
import { wechat } from "./wechat.mjs";
|
|
6
7
|
import { x } from "./x.mjs";
|
|
7
|
-
export { apple, facebook, github, google, wechat, x };
|
|
8
|
+
export { type AppleClientSecretOptions, apple, createAppleClientSecret, facebook, github, google, wechat, x };
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { apple } from "./apple.mjs";
|
|
2
|
+
import { createAppleClientSecret } from "./apple-client-secret.mjs";
|
|
2
3
|
import { facebook } from "./facebook.mjs";
|
|
3
4
|
import { github } from "./github.mjs";
|
|
4
5
|
import { google } from "./google.mjs";
|
|
5
6
|
import { wechat } from "./wechat.mjs";
|
|
6
7
|
import { x } from "./x.mjs";
|
|
7
|
-
export { apple, facebook, github, google, wechat, x };
|
|
8
|
+
export { apple, createAppleClientSecret, facebook, github, google, wechat, x };
|
package/dist/session/db.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"db.cjs","names":["MapSession","resolveIndexesFor","PRINCIPAL_NAME_INDEX_NAME"],"sources":["../../src/session/db.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\nimport { PRINCIPAL_NAME_INDEX_NAME, resolveIndexesFor } from './common';\nimport { MapSession } from './map-session';\nimport type { SessionRepository } from './types';\n\ninterface SessionEntity {\n primaryId: string;\n sessionId: string;\n creationTime: number;\n lastAccessTime: number;\n maxInactiveInterval: number;\n expiryTime: number;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n attributes: Record<string, any>;\n principalName?: string | null;\n}\n\nclass DBSession extends MapSession {\n public isNew: boolean;\n public primaryId: string;\n\n constructor(cached: MapSession, isNew: boolean) {\n super(cached);\n this.isNew = isNew;\n this.primaryId = randomUUID();\n }\n}\n\nexport interface DBAdapter {\n save(session: SessionEntity): Promise<void>;\n deleteById(sessionId: string): Promise<void>;\n findById(sessionId: string): Promise<SessionEntity | null>;\n findByPrincipalName(principalName: string): Promise<SessionEntity[]>;\n cleanupExpiredSessions(cleanupCount?: number): Promise<void>;\n}\n\nexport class DBIndexedSessionRepository implements SessionRepository<DBSession> {\n private defaultMaxInactiveInterval = 1800;\n private readonly db: DBAdapter;\n\n constructor(db: DBAdapter) {\n this.db = db;\n }\n\n setDefaultMaxInactiveInterval(interval: number) {\n this.defaultMaxInactiveInterval = interval;\n }\n\n private mapSessionToEntity(session: DBSession): SessionEntity {\n const attributes: Record<string, string | number | null> = {};\n for (const name of session.getAttributeNames()) {\n attributes[name] = session.getAttribute(name);\n }\n const principalName = resolveIndexesFor(session);\n\n return {\n primaryId: session.primaryId,\n sessionId: session.getId(),\n creationTime: session.getCreationTime(),\n lastAccessTime: session.getLastAccessedTime(),\n maxInactiveInterval: session.getMaxInactiveInterval(),\n expiryTime: session.getLastAccessedTime() + session.getMaxInactiveInterval() * 1000,\n attributes,\n principalName,\n };\n }\n\n private mapEntityToSession(entity: SessionEntity, allowExpired: boolean): DBSession | null {\n const loaded = new MapSession(entity.sessionId);\n loaded.setCreationTime(entity.creationTime);\n loaded.setLastAccessedTime(entity.lastAccessTime);\n loaded.setMaxInactiveInterval(entity.maxInactiveInterval);\n for (const [key, value] of Object.entries(entity.attributes)) {\n loaded.setAttribute(key, value);\n }\n\n if (!allowExpired && loaded.isExpired()) return null;\n const session = new DBSession(loaded, false);\n session.primaryId = entity.primaryId;\n return session;\n }\n\n private async getSession(id: string, allowExpired: boolean): Promise<DBSession | null> {\n const entity = await this.db.findById(id);\n if (!entity) return null;\n return this.mapEntityToSession(entity, allowExpired);\n }\n\n // override\n createSession() {\n const cached = new MapSession();\n cached.setMaxInactiveInterval(this.defaultMaxInactiveInterval);\n return new DBSession(cached, true);\n }\n\n async save(session: DBSession) {\n const entity = this.mapSessionToEntity(session);\n await this.db.save(entity);\n session.isNew = false;\n }\n\n async findById(sessionId: string): Promise<DBSession | null> {\n return this.getSession(sessionId, false);\n }\n\n async deleteById(sessionId: string) {\n await this.db.deleteById(sessionId);\n }\n\n async findByIndexNameAndIndexValue(\n indexName: string,\n indexValue: string\n ): Promise<Map<string, DBSession>> {\n if (indexName !== PRINCIPAL_NAME_INDEX_NAME) {\n return new Map<string, DBSession>();\n }\n const entities = await this.db.findByPrincipalName(indexValue);\n if (entities.length === 0) {\n return new Map<string, DBSession>();\n }\n const sessions = new Map<string, DBSession>();\n for (const entity of entities) {\n const session = this.mapEntityToSession(entity, false);\n if (session) {\n sessions.set(session.getId(), session);\n }\n }\n return sessions;\n }\n\n async findByPrincipalName(principalName: string): Promise<Map<string, DBSession>> {\n return this.findByIndexNameAndIndexValue(PRINCIPAL_NAME_INDEX_NAME, principalName);\n }\n\n async cleanupExpiredSessions(cleanupCount?: number): Promise<void> {\n return this.db.cleanupExpiredSessions(cleanupCount);\n }\n}\n"],"mappings":";;;;;AAiBA,IAAM,YAAN,cAAwBA,4BAAAA,WAAW;CACjC;CACA;CAEA,YAAY,QAAoB,OAAgB;EAC9C,MAAM,MAAM;EACZ,KAAK,QAAQ;EACb,KAAK,aAAA,
|
|
1
|
+
{"version":3,"file":"db.cjs","names":["MapSession","randomUUID","resolveIndexesFor","PRINCIPAL_NAME_INDEX_NAME"],"sources":["../../src/session/db.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\nimport { PRINCIPAL_NAME_INDEX_NAME, resolveIndexesFor } from './common';\nimport { MapSession } from './map-session';\nimport type { SessionRepository } from './types';\n\ninterface SessionEntity {\n primaryId: string;\n sessionId: string;\n creationTime: number;\n lastAccessTime: number;\n maxInactiveInterval: number;\n expiryTime: number;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n attributes: Record<string, any>;\n principalName?: string | null;\n}\n\nclass DBSession extends MapSession {\n public isNew: boolean;\n public primaryId: string;\n\n constructor(cached: MapSession, isNew: boolean) {\n super(cached);\n this.isNew = isNew;\n this.primaryId = randomUUID();\n }\n}\n\nexport interface DBAdapter {\n save(session: SessionEntity): Promise<void>;\n deleteById(sessionId: string): Promise<void>;\n findById(sessionId: string): Promise<SessionEntity | null>;\n findByPrincipalName(principalName: string): Promise<SessionEntity[]>;\n cleanupExpiredSessions(cleanupCount?: number): Promise<void>;\n}\n\nexport class DBIndexedSessionRepository implements SessionRepository<DBSession> {\n private defaultMaxInactiveInterval = 1800;\n private readonly db: DBAdapter;\n\n constructor(db: DBAdapter) {\n this.db = db;\n }\n\n setDefaultMaxInactiveInterval(interval: number) {\n this.defaultMaxInactiveInterval = interval;\n }\n\n private mapSessionToEntity(session: DBSession): SessionEntity {\n const attributes: Record<string, string | number | null> = {};\n for (const name of session.getAttributeNames()) {\n attributes[name] = session.getAttribute(name);\n }\n const principalName = resolveIndexesFor(session);\n\n return {\n primaryId: session.primaryId,\n sessionId: session.getId(),\n creationTime: session.getCreationTime(),\n lastAccessTime: session.getLastAccessedTime(),\n maxInactiveInterval: session.getMaxInactiveInterval(),\n expiryTime: session.getLastAccessedTime() + session.getMaxInactiveInterval() * 1000,\n attributes,\n principalName,\n };\n }\n\n private mapEntityToSession(entity: SessionEntity, allowExpired: boolean): DBSession | null {\n const loaded = new MapSession(entity.sessionId);\n loaded.setCreationTime(entity.creationTime);\n loaded.setLastAccessedTime(entity.lastAccessTime);\n loaded.setMaxInactiveInterval(entity.maxInactiveInterval);\n for (const [key, value] of Object.entries(entity.attributes)) {\n loaded.setAttribute(key, value);\n }\n\n if (!allowExpired && loaded.isExpired()) return null;\n const session = new DBSession(loaded, false);\n session.primaryId = entity.primaryId;\n return session;\n }\n\n private async getSession(id: string, allowExpired: boolean): Promise<DBSession | null> {\n const entity = await this.db.findById(id);\n if (!entity) return null;\n return this.mapEntityToSession(entity, allowExpired);\n }\n\n // override\n createSession() {\n const cached = new MapSession();\n cached.setMaxInactiveInterval(this.defaultMaxInactiveInterval);\n return new DBSession(cached, true);\n }\n\n async save(session: DBSession) {\n const entity = this.mapSessionToEntity(session);\n await this.db.save(entity);\n session.isNew = false;\n }\n\n async findById(sessionId: string): Promise<DBSession | null> {\n return this.getSession(sessionId, false);\n }\n\n async deleteById(sessionId: string) {\n await this.db.deleteById(sessionId);\n }\n\n async findByIndexNameAndIndexValue(\n indexName: string,\n indexValue: string\n ): Promise<Map<string, DBSession>> {\n if (indexName !== PRINCIPAL_NAME_INDEX_NAME) {\n return new Map<string, DBSession>();\n }\n const entities = await this.db.findByPrincipalName(indexValue);\n if (entities.length === 0) {\n return new Map<string, DBSession>();\n }\n const sessions = new Map<string, DBSession>();\n for (const entity of entities) {\n const session = this.mapEntityToSession(entity, false);\n if (session) {\n sessions.set(session.getId(), session);\n }\n }\n return sessions;\n }\n\n async findByPrincipalName(principalName: string): Promise<Map<string, DBSession>> {\n return this.findByIndexNameAndIndexValue(PRINCIPAL_NAME_INDEX_NAME, principalName);\n }\n\n async cleanupExpiredSessions(cleanupCount?: number): Promise<void> {\n return this.db.cleanupExpiredSessions(cleanupCount);\n }\n}\n"],"mappings":";;;;;AAiBA,IAAM,YAAN,cAAwBA,4BAAAA,WAAW;CACjC;CACA;CAEA,YAAY,QAAoB,OAAgB;EAC9C,MAAM,MAAM;EACZ,KAAK,QAAQ;EACb,KAAK,aAAA,GAAYC,YAAAA,WAAAA,CAAW;CAC9B;AACF;AAUA,IAAa,6BAAb,MAAgF;CAC9E,6BAAqC;CACrC;CAEA,YAAY,IAAe;EACzB,KAAK,KAAK;CACZ;CAEA,8BAA8B,UAAkB;EAC9C,KAAK,6BAA6B;CACpC;CAEA,mBAA2B,SAAmC;EAC5D,MAAM,aAAqD,CAAC;EAC5D,KAAK,MAAM,QAAQ,QAAQ,kBAAkB,GAC3C,WAAW,QAAQ,QAAQ,aAAa,IAAI;EAE9C,MAAM,gBAAgBC,uBAAAA,kBAAkB,OAAO;EAE/C,OAAO;GACL,WAAW,QAAQ;GACnB,WAAW,QAAQ,MAAM;GACzB,cAAc,QAAQ,gBAAgB;GACtC,gBAAgB,QAAQ,oBAAoB;GAC5C,qBAAqB,QAAQ,uBAAuB;GACpD,YAAY,QAAQ,oBAAoB,IAAI,QAAQ,uBAAuB,IAAI;GAC/E;GACA;EACF;CACF;CAEA,mBAA2B,QAAuB,cAAyC;EACzF,MAAM,SAAS,IAAIF,4BAAAA,WAAW,OAAO,SAAS;EAC9C,OAAO,gBAAgB,OAAO,YAAY;EAC1C,OAAO,oBAAoB,OA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wD;EAChF,OAAO,KAAK,6BAA6BA,uBAAAA,2BAA2B,aAAa;CACnF;CAEA,MAAM,uBAAuB,cAAsC;EACjE,OAAO,KAAK,GAAG,uBAAuB,YAAY;CACpD;AACF"}
|
|
@@ -12,7 +12,7 @@ var MapSession = class {
|
|
|
12
12
|
lastAccessedTime = this.creationTime;
|
|
13
13
|
maxInactiveInterval = DEFAULT_MAX_INACTIVE_INTERVAL;
|
|
14
14
|
constructor(input) {
|
|
15
|
-
if (
|
|
15
|
+
if (input === void 0) this.id = generateId();
|
|
16
16
|
else if (typeof input === "string") this.id = input;
|
|
17
17
|
else {
|
|
18
18
|
const session = input;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"map-session.cjs","names":[],"sources":["../../src/session/map-session.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\nimport type { Session } from './types';\n\nfunction generateId() {\n return randomUUID();\n}\n\nconst DEFAULT_MAX_INACTIVE_INTERVAL = 1800;\n\nexport class MapSession implements Session {\n private id: string;\n private readonly sessionAttrs = new Map<string, string | number>();\n private creationTime = Date.now();\n private lastAccessedTime = this.creationTime;\n private maxInactiveInterval = DEFAULT_MAX_INACTIVE_INTERVAL;\n\n constructor(id?: string);\n constructor(session: Session);\n constructor(input?: string | Session) {\n if (
|
|
1
|
+
{"version":3,"file":"map-session.cjs","names":["randomUUID"],"sources":["../../src/session/map-session.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\nimport type { Session } from './types';\n\nfunction generateId() {\n return randomUUID();\n}\n\nconst DEFAULT_MAX_INACTIVE_INTERVAL = 1800;\n\nexport class MapSession implements Session {\n private id: string;\n private readonly sessionAttrs = new Map<string, string | number>();\n private creationTime = Date.now();\n private lastAccessedTime = this.creationTime;\n private maxInactiveInterval = DEFAULT_MAX_INACTIVE_INTERVAL;\n\n constructor(id?: string);\n constructor(session: Session);\n constructor(input?: string | Session) {\n if (input === undefined) {\n this.id = generateId();\n } else if (typeof input === 'string') {\n this.id = input;\n } else {\n const session = input;\n this.id = session.getId();\n\n for (const attrName of session.getAttributeNames()) {\n const attrValue = session.getAttribute(attrName);\n if (attrValue !== null) {\n this.setAttribute(attrName, attrValue);\n }\n }\n\n this.lastAccessedTime = session.getLastAccessedTime();\n this.creationTime = session.getCreationTime();\n this.maxInactiveInterval = session.getMaxInactiveInterval();\n }\n }\n\n setCreationTime(creationTime: number) {\n this.creationTime = creationTime;\n }\n\n // override\n getId() {\n return this.id;\n }\n\n changeSessionId() {\n const changedId = generateId();\n this.id = changedId;\n return changedId;\n }\n\n getAttribute(name: string) {\n return this.sessionAttrs.get(name) ?? null;\n }\n\n getAttributeNames(): string[] {\n return Array.from(this.sessionAttrs.keys());\n }\n\n setAttribute(name: string, value: string | number | null) {\n if (value === null) {\n this.removeAttribute(name);\n } else {\n this.sessionAttrs.set(name, value);\n }\n }\n\n removeAttribute(name: string) {\n this.sessionAttrs.delete(name);\n }\n\n getCreationTime() {\n return this.creationTime;\n }\n\n getLastAccessedTime() {\n return this.lastAccessedTime;\n }\n\n setLastAccessedTime(lastAccessedTime: number) {\n this.lastAccessedTime = lastAccessedTime;\n }\n\n getMaxInactiveInterval() {\n return this.maxInactiveInterval;\n }\n\n setMaxInactiveInterval(interval: number) {\n this.maxInactiveInterval = interval;\n }\n\n isExpired() {\n if (this.maxInactiveInterval < 0) return false;\n return Date.now() - this.maxInactiveInterval * 1000 - this.lastAccessedTime >= 0;\n }\n}\n"],"mappings":";;;AAGA,SAAS,aAAa;CACpB,QAAA,GAAOA,YAAAA,WAAAA,CAAW;AACpB;AAEA,MAAM,gCAAgC;AAEtC,IAAa,aAAb,MAA2C;CACzC;CACA,+BAAgC,IAAI,IAA6B;CACjE,eAAuB,KAAK,IAAI;CAChC,mBAA2B,KAAK;CAChC,sBAA8B;CAI9B,YAAY,OAA0B;EACpC,IAAI,UAAU,KAAA,GACZ,KAAK,KAAK,WAAW;OAChB,IAAI,OAAO,UAAU,UAC1B,KAAK,KAAK;OACL;GACL,MAAM,U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13
|
constructor(input) {
|
|
14
|
-
if (
|
|
14
|
+
if (input === void 0) this.id = generateId();
|
|
15
15
|
else if (typeof input === "string") this.id = input;
|
|
16
16
|
else {
|
|
17
17
|
const session = input;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"map-session.mjs","names":[],"sources":["../../src/session/map-session.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\nimport type { Session } from './types';\n\nfunction generateId() {\n return randomUUID();\n}\n\nconst DEFAULT_MAX_INACTIVE_INTERVAL = 1800;\n\nexport class MapSession implements Session {\n private id: string;\n private readonly sessionAttrs = new Map<string, string | number>();\n private creationTime = Date.now();\n private lastAccessedTime = this.creationTime;\n private maxInactiveInterval = DEFAULT_MAX_INACTIVE_INTERVAL;\n\n constructor(id?: string);\n constructor(session: Session);\n constructor(input?: string | Session) {\n if (
|
|
1
|
+
{"version":3,"file":"map-session.mjs","names":[],"sources":["../../src/session/map-session.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\nimport type { Session } from './types';\n\nfunction generateId() {\n return randomUUID();\n}\n\nconst DEFAULT_MAX_INACTIVE_INTERVAL = 1800;\n\nexport class MapSession implements Session {\n private id: string;\n private readonly sessionAttrs = new Map<string, string | number>();\n private creationTime = Date.now();\n private lastAccessedTime = this.creationTime;\n private maxInactiveInterval = DEFAULT_MAX_INACTIVE_INTERVAL;\n\n constructor(id?: string);\n constructor(session: Session);\n constructor(input?: string | Session) {\n if (input === undefined) {\n this.id = generateId();\n } else if (typeof input === 'string') {\n this.id = input;\n } else {\n const session = input;\n this.id = session.getId();\n\n for (const attrName of session.getAttributeNames()) {\n const attrValue = session.getAttribute(attrName);\n if (attrValue !== null) {\n this.setAttribute(attrName, attrValue);\n }\n }\n\n this.lastAccessedTime = session.getLastAccessedTime();\n this.creationTime = session.getCreationTime();\n this.maxInactiveInterval = session.getMaxInactiveInterval();\n }\n }\n\n setCreationTime(creationTime: number) {\n this.creationTime = creationTime;\n }\n\n // override\n getId() {\n return this.id;\n }\n\n changeSessionId() {\n const changedId = generateId();\n this.id = changedId;\n return changedId;\n }\n\n getAttribute(name: string) {\n return this.sessionAttrs.get(name) ?? null;\n }\n\n getAttributeNames(): string[] {\n return Array.from(this.sessionAttrs.keys());\n }\n\n setAttribute(name: string, value: string | number | null) {\n if (value === null) {\n this.removeAttribute(name);\n } else {\n this.sessionAttrs.set(name, value);\n }\n }\n\n removeAttribute(name: string) {\n this.sessionAttrs.delete(name);\n }\n\n getCreationTime() {\n return this.creationTime;\n }\n\n getLastAccessedTime() {\n return this.lastAccessedTime;\n }\n\n setLastAccessedTime(lastAccessedTime: number) {\n this.lastAccessedTime = lastAccessedTime;\n }\n\n getMaxInactiveInterval() {\n return this.maxInactiveInterval;\n }\n\n setMaxInactiveInterval(interval: number) {\n this.maxInactiveInterval = interval;\n }\n\n isExpired() {\n if (this.maxInactiveInterval < 0) return false;\n return Date.now() - this.maxInactiveInterval * 1000 - this.lastAccessedTime >= 0;\n }\n}\n"],"mappings":";;AAGA,SAAS,aAAa;CACpB,OAAO,WAAW;AACpB;AAEA,MAAM,gCAAgC;AAEtC,IAAa,aAAb,MAA2C;CACzC;CACA,+BAAgC,IAAI,IAA6B;CACjE,eAAuB,KAAK,IAAI;CAChC,mBAA2B,KAAK;CAChC,sBAA8B;CAI9B,YAAY,OAA0B;EACpC,IAAI,UAAU,KAAA,GACZ,KAAK,KAAK,WAAW;OAChB,IAAI,OAAO,UAAU,UAC1B,KAAK,KAAK;OACL;GACL,MAAM,UAAU;GAChB,KAAK,KAAK,QAAQ,MAAM;GAExB,KAAK,MAAM,YAAY,QAAQ,kBAAkB,GAAG;IAClD,MAAM,YAAY,QAAQ,aAAa,QAAQ;IAC/C,IAAI,cAAc,MAChB,KAAK,aAAa,UAAU,SAAS;GAEzC;GAEA,KAAK,mBAAmB,QAAQ,oBAAoB;GACpD,KAAK,eAAe,QAAQ,gBAAgB;GAC5C,KAAK,sBAAsB,QAAQ,uBAAuB;EAC5D;CACF;CAEA,gBAAgB,cAAsB;EACpC,KAAK,eAAe;CACtB;CAGA,QAAQ;EACN,OAAO,KAAK;CACd;CAEA,kBAAkB;EAChB,MAAM,YAAY,WAAW;EAC7B,KAAK,KAAK;EACV,OAAO;CACT;CAEA,aAAa,MAAc;EACzB,OAAO,KAAK,aAAa,IAAI,IAAI,KAAK;CACxC;CAEA,oBAA8B;EAC5B,OAAO,MAAM,KAAK,KAAK,aAAa,KAAK,CAAC;CAC5C;CAEA,aAAa,MAAc,OAA+B;EACxD,IAAI,UAAU,MACZ,KAAK,gBAAgB,IAAI;OAEzB,KAAK,aAAa,IAAI,MAAM,KAAK;CAErC;CAEA,gBAAgB,MAAc;EAC5B,KAAK,aAAa,OAAO,IAAI;CAC/B;CAEA,kBAAkB;EAChB,OAAO,KAAK;CACd;CAEA,sBAAsB;EACpB,OAAO,KAAK;CACd;CAEA,oBAAoB,kBAA0B;EAC5C,KAAK,mBAAmB;CAC1B;CAEA,yBAAyB;EACvB,OAAO,KAAK;CACd;CAEA,uBAAuB,UAAkB;EACvC,KAAK,sBAAsB;CAC7B;CAEA,YAAY;EACV,IAAI,KAAK,sBAAsB,GAAG,OAAO;EACzC,OAAO,KAAK,IAAI,IAAI,KAAK,sBAAsB,MAAO,KAAK,oBAAoB;CACjF;AACF"}
|
package/dist/session/redis.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"redis.cjs","names":["resolveIndexesFor","PRINCIPAL_NAME_INDEX_NAME","MapSession","SPRING_SECURITY_CONTEXT"],"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 === 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,wBAAwBA,uBAAAA,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,oBAAoB,kBAA0B;EAC5C,KAAK,OAAO,oBAAoB,gBAAgB;EAChD,KAAK,MAAM,IAAI,wBAAwB,gBAAgB;CACzD;CAEA,YAAY;EACV,OAAO,KAAK,OAAO,UAAU;CAC/B;CAEA,kBAAkB;EAChB,OAAO,KAAK,OAAO,gBAAgB;CACrC;CAEA,QAAQ;EACN,OAAO,KAAK,OAAO,MAAM;CAC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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,6BAA6BA,uBAAAA,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"}
|
|
1
|
+
{"version":3,"file":"redis.cjs","names":["resolveIndexesFor","PRINCIPAL_NAME_INDEX_NAME","MapSession","SPRING_SECURITY_CONTEXT"],"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 === 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 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,wBAAwBA,uBAAAA,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,oBAAoB,kBAA0B;EAC5C,KAAK,OAAO,oBAAoB,gBAAgB;EAChD,KAAK,MAAM,IAAI,wBAAwB,gBAAgB;CACzD;CAEA,YAAY;EACV,OAAO,KAAK,OAAO,UAAU;CAC/B;CAEA,kBAAkB;EAChB,OAAO,KAAK,OAAO,gBAAgB;CACrC;CAEA,QAAQ;EACN,OAAO,KAAK,OAAO,MAAM;CAC3B;CAEA,kBAAkB;EAChB,OAAO,KAAK,OAAO,gBAAgB;CACrC;CAEA,sBAAsB;EACpB,OAAO,KAAK,OAAO,oBAAoB;CACzC;CAEA,uBAAuB,UAAkB;EACvC,KAAK,OAAO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ACT;CAEA,MAAM,oBAAoB,eAAuB;EAC/C,OAAO,KAAK,6BAA6BA,uBAAAA,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,KAAK,MAAM,IAAI,GAAG;CAC3B;CAEA,MAAM,WAAW,KAAa;EAC5B,MAAM,KAAK,MAAM,IAAI,GAAG;CAC1B;AACF"}
|
package/dist/session/redis.mjs
CHANGED
|
@@ -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 === 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;AAC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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"}
|
|
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 === 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 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;GA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-1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"http.cjs","names":["cookie"],"sources":["../../src/utils/http.ts"],"sourcesContent":["import { type SerializeOptions, parseCookie, stringifySetCookie } from 'cookie';\nimport { match } from 'path-to-regexp';\n\nexport type CookieOptions = Omit<SerializeOptions, 'encode'>;\n\nexport function getCookie(request: Request, name: string): string | undefined {\n const cookie = request.headers.get('Cookie');\n if (!cookie) return undefined;\n const parsed = parseCookie(cookie);\n return parsed[name];\n}\n\nexport function setCookie(\n response: Response,\n name: string,\n value: string,\n options?: SerializeOptions\n) {\n response.headers.append('Set-Cookie', stringifySetCookie({ name, value, ...options }));\n}\n\nexport function deleteCookie(response: Response, name: string, options?: SerializeOptions) {\n response.headers.append(\n 'Set-Cookie',\n stringifySetCookie({ name, value: '', ...options, maxAge: 0 })\n );\n}\n\ntype PathParam<T extends string> = T extends `${string}:${infer Param}/${infer Rest}`\n ? { [K in Param]: string } & PathParam<Rest>\n : T extends `${string}:${infer Param}`\n ? { [K in Param]: string }\n : // eslint-disable-next-line @typescript-eslint/no-empty-object-type\n {};\n\nexport function param<P extends string>(request: Request, path: P): PathParam<P> {\n const url = new URL(request.url);\n const fn = match(path);\n const result = fn(url.pathname);\n if (!result) throw new Error(`Path not matched: ${url.pathname}, path: ${path}`);\n return result.params as PathParam<P>;\n}\n\nexport function query(request: Request) {\n const url = new URL(request.url);\n return Object.fromEntries(url.searchParams.entries());\n}\n"],"mappings":";;;;AAKA,SAAgB,UAAU,SAAkB,MAAkC;CAC5E,MAAMA,WAAS,QAAQ,QAAQ,IAAI,QAAQ;CAC3C,IAAI,CAACA,UAAQ,OAAO,KAAA;CAEpB,QAAA,
|
|
1
|
+
{"version":3,"file":"http.cjs","names":["cookie","parseCookie","stringifySetCookie","match"],"sources":["../../src/utils/http.ts"],"sourcesContent":["import { type SerializeOptions, parseCookie, stringifySetCookie } from 'cookie';\nimport { match } from 'path-to-regexp';\n\nexport type CookieOptions = Omit<SerializeOptions, 'encode'>;\n\nexport function getCookie(request: Request, name: string): string | undefined {\n const cookie = request.headers.get('Cookie');\n if (!cookie) return undefined;\n const parsed = parseCookie(cookie);\n return parsed[name];\n}\n\nexport function setCookie(\n response: Response,\n name: string,\n value: string,\n options?: SerializeOptions\n) {\n response.headers.append('Set-Cookie', stringifySetCookie({ name, value, ...options }));\n}\n\nexport function deleteCookie(response: Response, name: string, options?: SerializeOptions) {\n response.headers.append(\n 'Set-Cookie',\n stringifySetCookie({ name, value: '', ...options, maxAge: 0 })\n );\n}\n\ntype PathParam<T extends string> = T extends `${string}:${infer Param}/${infer Rest}`\n ? { [K in Param]: string } & PathParam<Rest>\n : T extends `${string}:${infer Param}`\n ? { [K in Param]: string }\n : // eslint-disable-next-line @typescript-eslint/no-empty-object-type\n {};\n\nexport function param<P extends string>(request: Request, path: P): PathParam<P> {\n const url = new URL(request.url);\n const fn = match(path);\n const result = fn(url.pathname);\n if (!result) throw new Error(`Path not matched: ${url.pathname}, path: ${path}`);\n return result.params as PathParam<P>;\n}\n\nexport function query(request: Request) {\n const url = new URL(request.url);\n return Object.fromEntries(url.searchParams.entries());\n}\n"],"mappings":";;;;AAKA,SAAgB,UAAU,SAAkB,MAAkC;CAC5E,MAAMA,WAAS,QAAQ,QAAQ,IAAI,QAAQ;CAC3C,IAAI,CAACA,UAAQ,OAAO,KAAA;CAEpB,QAAA,GADeC,OAAAA,YAAAA,CAAYD,QACf,CAAC,CAAC;AAChB;AAEA,SAAgB,UACd,UACA,MACA,OACA,SACA;CACA,SAAS,QAAQ,OAAO,eAAA,GAAcE,OAAAA,mBAAAA,CAAmB;EAAE;EAAM;EAAO,GAAG;CAAQ,CAAC,CAAC;AACvF;AAEA,SAAgB,aAAa,UAAoB,MAAc,SAA4B;CACzF,SAAS,QAAQ,OACf,eAAA,GACAA,OAAAA,mBAAAA,CAAmB;EAAE;EAAM,OAAO;EAAI,GAAG;EAAS,QAAQ;CAAE,CAAC,CAC/D;AACF;AASA,SAAgB,MAAwB,SAAkB,MAAuB;CAC/E,MAAM,MAAM,IAAI,IAAI,QAAQ,GAAG;CAE/B,MAAM,UAAA,GADKC,eAAAA,MAAAA,CAAM,IACD,CAAC,CAAC,IAAI,QAAQ;CAC9B,IAAI,CAAC,QAAQ,MAAM,IAAI,MAAM,qBAAqB,IAAI,SAAS,UAAU,MAAM;CAC/E,OAAO,OAAO;AAChB;AAEA,SAAgB,MAAM,SAAkB;CACtC,MAAM,MAAM,IAAI,IAAI,QAAQ,GAAG;CAC/B,OAAO,OAAO,YAAY,IAAI,aAAa,QAAQ,CAAC;AACtD"}
|