@shware/security 5.0.0 → 6.0.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/README.md +32 -1
- package/dist/auth/index.cjs +32 -3
- package/dist/auth/index.cjs.map +1 -1
- package/dist/auth/index.d.cts +5 -1
- package/dist/auth/index.d.cts.map +1 -1
- package/dist/auth/index.d.mts +5 -1
- package/dist/auth/index.d.mts.map +1 -1
- package/dist/auth/index.mjs +33 -4
- package/dist/auth/index.mjs.map +1 -1
- package/dist/auth/types.d.cts +13 -0
- package/dist/auth/types.d.cts.map +1 -1
- package/dist/auth/types.d.mts +13 -0
- package/dist/auth/types.d.mts.map +1 -1
- package/dist/email/schema.cjs +9 -2
- package/dist/email/schema.cjs.map +1 -1
- package/dist/email/schema.d.cts +2 -2
- package/dist/email/schema.d.cts.map +1 -1
- package/dist/email/schema.d.mts +2 -2
- package/dist/email/schema.d.mts.map +1 -1
- package/dist/email/schema.mjs +10 -3
- package/dist/email/schema.mjs.map +1 -1
- package/dist/oauth2/provider/common.cjs +1 -0
- package/dist/oauth2/provider/common.cjs.map +1 -1
- package/dist/oauth2/provider/common.d.cts +2 -0
- package/dist/oauth2/provider/common.d.cts.map +1 -1
- package/dist/oauth2/provider/common.d.mts +2 -0
- package/dist/oauth2/provider/common.d.mts.map +1 -1
- package/dist/oauth2/provider/common.mjs +1 -0
- package/dist/oauth2/provider/common.mjs.map +1 -1
- package/dist/oauth2/provider/github.cjs +27 -5
- package/dist/oauth2/provider/github.cjs.map +1 -1
- package/dist/oauth2/provider/github.d.cts.map +1 -1
- package/dist/oauth2/provider/github.d.mts.map +1 -1
- package/dist/oauth2/provider/github.mjs +27 -5
- package/dist/oauth2/provider/github.mjs.map +1 -1
- package/dist/session/redis.cjs +9 -0
- package/dist/session/redis.cjs.map +1 -1
- package/dist/session/redis.d.cts +1 -0
- package/dist/session/redis.d.cts.map +1 -1
- package/dist/session/redis.d.mts +1 -0
- package/dist/session/redis.d.mts.map +1 -1
- package/dist/session/redis.mjs +9 -0
- package/dist/session/redis.mjs.map +1 -1
- package/dist/session/types.d.cts +11 -0
- package/dist/session/types.d.cts.map +1 -1
- package/dist/session/types.d.mts +11 -0
- package/dist/session/types.d.mts.map +1 -1
- package/dist/utils/valid.cjs +12 -0
- package/dist/utils/valid.cjs.map +1 -1
- package/dist/utils/valid.d.cts +1 -0
- package/dist/utils/valid.d.cts.map +1 -1
- package/dist/utils/valid.d.mts +1 -0
- package/dist/utils/valid.d.mts.map +1 -1
- package/dist/utils/valid.mjs +12 -1
- package/dist/utils/valid.mjs.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"github.cjs","names":["createAuthorizationUri","exchangeAuthorizationCode","OAuth2Error"],"sources":["../../../src/oauth2/provider/github.ts"],"sourcesContent":["import { invariant } from '@shware/utils';\nimport { OAuth2Error } from '../error';\nimport type { OAuth2Token, Provider } from '../types';\nimport { createAuthorizationUri, exchangeAuthorizationCode } from './common';\n\nexport function createGithubProvider(): Provider {\n return {\n authorizationUri: 'https://github.com/login/oauth/authorize',\n tokenUri: 'https://github.com/login/oauth/access_token',\n userInfoUri: 'https://api.github.com/user',\n userNameAttribute: 'id',\n defaultScope: ['user:email'],\n createAuthorizationUri({ pkce: _, ...params }) {\n return createAuthorizationUri({\n ...params,\n scope: params.scope ?? this.defaultScope,\n authorizationUri: this.authorizationUri,\n });\n },\n async exchangeAuthorizationCode({ pkce: _, ...params }) {\n const response = await exchangeAuthorizationCode({
|
|
1
|
+
{"version":3,"file":"github.cjs","names":["createAuthorizationUri","exchangeAuthorizationCode","OAuth2Error"],"sources":["../../../src/oauth2/provider/github.ts"],"sourcesContent":["import { invariant } from '@shware/utils';\nimport { OAuth2Error } from '../error';\nimport type { OAuth2Token, Provider } from '../types';\nimport { createAuthorizationUri, exchangeAuthorizationCode } from './common';\n\n/**\n * GitHub's REST API rejects any request without a `User-Agent` header with a 403. Node's fetch sends\n * a default one, but Cloudflare Workers' fetch sends none, so every GitHub request sets it explicitly.\n * reference: https://docs.github.com/en/rest/using-the-rest-api/troubleshooting-the-rest-api#user-agent-required\n */\nconst USER_AGENT = '@shware/security';\n\n/** A short slice of an error response body, enough to tell GitHub's failures apart in logs. */\nasync function describeFailure(response: Response, message: string) {\n const body = await response.text().catch(() => '');\n const detail = body ? `: ${body.slice(0, 200)}` : '';\n return `${message} (HTTP ${response.status})${detail}`;\n}\n\nexport function createGithubProvider(): Provider {\n return {\n authorizationUri: 'https://github.com/login/oauth/authorize',\n tokenUri: 'https://github.com/login/oauth/access_token',\n userInfoUri: 'https://api.github.com/user',\n userNameAttribute: 'id',\n defaultScope: ['user:email'],\n createAuthorizationUri({ pkce: _, ...params }) {\n return createAuthorizationUri({\n ...params,\n scope: params.scope ?? this.defaultScope,\n authorizationUri: this.authorizationUri,\n });\n },\n async exchangeAuthorizationCode({ pkce: _, ...params }) {\n const response = await exchangeAuthorizationCode({\n ...params,\n tokenUri: this.tokenUri,\n headers: { 'User-Agent': USER_AGENT },\n });\n if (!response.ok) {\n const { error, error_description } = (await response.json()) as GithubErrorResponse;\n throw new OAuth2Error(response.status, error, error_description);\n }\n // GitHub answers a failed exchange (bad_verification_code, incorrect_client_credentials, ...)\n // with HTTP 200 and an error body, so a 200 alone does not mean a token was issued.\n const body = (await response.json()) as GithubToken & Partial<GithubErrorResponse>;\n if (body.error) throw new OAuth2Error(400, body.error, body.error_description);\n return body;\n },\n async getUserInfo({ access_token }) {\n invariant(access_token, 'access_token is required');\n invariant(this.userInfoUri, 'userInfoUri is required');\n const headers = {\n Accept: 'application/json',\n Authorization: `Bearer ${access_token}`,\n 'User-Agent': USER_AGENT,\n };\n const response = await fetch(this.userInfoUri, { headers });\n if (!response.ok) {\n const message = await describeFailure(response, 'Failed to fetch user info');\n throw new OAuth2Error(response.status, 'invalid_request', message);\n }\n const data = (await response.json()) as GithubUserInfo;\n const emailResponse = await fetch('https://api.github.com/user/emails', { headers });\n if (!emailResponse.ok) {\n const message = await describeFailure(emailResponse, 'Failed to fetch user email');\n throw new OAuth2Error(emailResponse.status, 'invalid_request', message);\n }\n const emails = (await emailResponse.json()) as GithubEmail[];\n data.email = emails.find((email) => email.primary)?.email || data.email;\n const email_verified = emails.find((email) => email.email === data.email)?.verified ?? false;\n return {\n data,\n claims: {\n sub: data.id,\n name: data.name || data.login,\n email_verified,\n email: data.email,\n picture: data.avatar_url,\n profile: data.html_url,\n website: data.html_url,\n updated_at: data.updated_at ? Date.parse(data.updated_at) : undefined,\n },\n };\n },\n };\n}\n\nexport const github = createGithubProvider();\n\nexport interface GithubUserInfo {\n login: string;\n id: string;\n node_id: string;\n avatar_url: string;\n gravatar_id: string;\n url: string;\n html_url: string;\n followers_url: string;\n following_url: string;\n gists_url: string;\n starred_url: string;\n subscriptions_url: string;\n organizations_url: string;\n repos_url: string;\n events_url: string;\n received_events_url: string;\n type: string;\n site_admin: boolean;\n name: string;\n company: string;\n blog: string;\n location: string;\n email: string;\n hireable: boolean;\n bio: string;\n twitter_username: string;\n public_repos: string;\n public_gists: string;\n followers: string;\n following: string;\n created_at: string;\n updated_at: string;\n private_gists: string;\n total_private_repos: string;\n owned_private_repos: string;\n disk_usage: string;\n collaborators: string;\n two_factor_authentication: boolean;\n plan: {\n name: string;\n space: string;\n private_repos: string;\n collaborators: string;\n };\n}\n\ninterface GithubEmail {\n email: string;\n primary: boolean;\n verified: boolean;\n visibility: 'public' | 'private';\n}\n\nexport interface GithubToken extends OAuth2Token {\n access_token: string;\n token_type: string;\n scope: string;\n expires_in: number;\n refresh_token: string;\n}\n\ninterface GithubErrorResponse {\n error: string;\n error_description: string;\n error_uri: string;\n}\n"],"mappings":";;;;;;;;;;AAUA,MAAM,aAAa;;AAGnB,eAAe,gBAAgB,UAAoB,SAAiB;CAClE,MAAM,OAAO,MAAM,SAAS,KAAK,CAAC,CAAC,YAAY,EAAE;CACjD,MAAM,SAAS,OAAO,KAAK,KAAK,MAAM,GAAG,GAAG,MAA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gBAAgB,MAAM,MAAM,sCAAsC,EAAE,QAAQ,CAAC;GACnF,IAAI,CAAC,cAAc,IAAI;IACrB,MAAM,UAAU,MAAM,gBAAgB,eAAe,4BAA4B;IACjF,MAAM,IAAIA,qBAAAA,YAAY,cAAc,QAAQ,mBAAmB,OAAO;GACxE;GACA,MAAM,SAAU,MAAM,cAAc,KAAK;GACzC,KAAK,QAAQ,OAAO,MAAM,UAAU,MAAM,OAAO,CAAC,EAAE,SAAS,KAAK;GAClE,MAAM,iBAAiB,OAAO,MAAM,UAAU,MAAM,UAAU,KAAK,KAAK,CAAC,EAAE,YAAY;GACvF,OAAO;IACL;IACA,QAAQ;KACN,KAAK,KAAK;KACV,MAAM,KAAK,QAAQ,KAAK;KACxB;KACA,OAAO,KAAK;KACZ,SAAS,KAAK;KACd,SAAS,KAAK;KACd,SAAS,KAAK;KACd,YAAY,KAAK,aAAa,KAAK,MAAM,KAAK,UAAU,IAAI,KAAA;IAC9D;GACF;EACF;CACF;AACF;AAEA,MAAa,SAAS,qBAAqB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"github.d.cts","names":[],"sources":["../../../src/oauth2/provider/github.ts"],"mappings":";;
|
|
1
|
+
{"version":3,"file":"github.d.cts","names":[],"sources":["../../../src/oauth2/provider/github.ts"],"mappings":";;wBAmBgB,wBAAwB;qBAqE3B,QAAM;iBAEF;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;IACE;IACA;IACA;IACA;;;iBAWa,oBAAoB;EACnC;EACA;EACA;EACA;EACA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"github.d.mts","names":[],"sources":["../../../src/oauth2/provider/github.ts"],"mappings":";;
|
|
1
|
+
{"version":3,"file":"github.d.mts","names":[],"sources":["../../../src/oauth2/provider/github.ts"],"mappings":";;wBAmBgB,wBAAwB;qBAqE3B,QAAM;iBAEF;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;IACE;IACA;IACA;IACA;;;iBAWa,oBAAoB;EACnC;EACA;EACA;EACA;EACA"}
|
|
@@ -2,6 +2,18 @@ import { OAuth2Error } from "../error.mjs";
|
|
|
2
2
|
import { createAuthorizationUri, exchangeAuthorizationCode } from "./common.mjs";
|
|
3
3
|
import { invariant } from "@shware/utils";
|
|
4
4
|
//#region src/oauth2/provider/github.ts
|
|
5
|
+
/**
|
|
6
|
+
* GitHub's REST API rejects any request without a `User-Agent` header with a 403. Node's fetch sends
|
|
7
|
+
* a default one, but Cloudflare Workers' fetch sends none, so every GitHub request sets it explicitly.
|
|
8
|
+
* reference: https://docs.github.com/en/rest/using-the-rest-api/troubleshooting-the-rest-api#user-agent-required
|
|
9
|
+
*/
|
|
10
|
+
const USER_AGENT = "@shware/security";
|
|
11
|
+
/** A short slice of an error response body, enough to tell GitHub's failures apart in logs. */
|
|
12
|
+
async function describeFailure(response, message) {
|
|
13
|
+
const body = await response.text().catch(() => "");
|
|
14
|
+
const detail = body ? `: ${body.slice(0, 200)}` : "";
|
|
15
|
+
return `${message} (HTTP ${response.status})${detail}`;
|
|
16
|
+
}
|
|
5
17
|
function createGithubProvider() {
|
|
6
18
|
return {
|
|
7
19
|
authorizationUri: "https://github.com/login/oauth/authorize",
|
|
@@ -19,26 +31,36 @@ function createGithubProvider() {
|
|
|
19
31
|
async exchangeAuthorizationCode({ pkce: _, ...params }) {
|
|
20
32
|
const response = await exchangeAuthorizationCode({
|
|
21
33
|
...params,
|
|
22
|
-
tokenUri: this.tokenUri
|
|
34
|
+
tokenUri: this.tokenUri,
|
|
35
|
+
headers: { "User-Agent": USER_AGENT }
|
|
23
36
|
});
|
|
24
37
|
if (!response.ok) {
|
|
25
38
|
const { error, error_description } = await response.json();
|
|
26
39
|
throw new OAuth2Error(response.status, error, error_description);
|
|
27
40
|
}
|
|
28
|
-
|
|
41
|
+
const body = await response.json();
|
|
42
|
+
if (body.error) throw new OAuth2Error(400, body.error, body.error_description);
|
|
43
|
+
return body;
|
|
29
44
|
},
|
|
30
45
|
async getUserInfo({ access_token }) {
|
|
31
46
|
invariant(access_token, "access_token is required");
|
|
32
47
|
invariant(this.userInfoUri, "userInfoUri is required");
|
|
33
48
|
const headers = {
|
|
34
49
|
Accept: "application/json",
|
|
35
|
-
Authorization: `Bearer ${access_token}
|
|
50
|
+
Authorization: `Bearer ${access_token}`,
|
|
51
|
+
"User-Agent": USER_AGENT
|
|
36
52
|
};
|
|
37
53
|
const response = await fetch(this.userInfoUri, { headers });
|
|
38
|
-
if (!response.ok)
|
|
54
|
+
if (!response.ok) {
|
|
55
|
+
const message = await describeFailure(response, "Failed to fetch user info");
|
|
56
|
+
throw new OAuth2Error(response.status, "invalid_request", message);
|
|
57
|
+
}
|
|
39
58
|
const data = await response.json();
|
|
40
59
|
const emailResponse = await fetch("https://api.github.com/user/emails", { headers });
|
|
41
|
-
if (!emailResponse.ok)
|
|
60
|
+
if (!emailResponse.ok) {
|
|
61
|
+
const message = await describeFailure(emailResponse, "Failed to fetch user email");
|
|
62
|
+
throw new OAuth2Error(emailResponse.status, "invalid_request", message);
|
|
63
|
+
}
|
|
42
64
|
const emails = await emailResponse.json();
|
|
43
65
|
data.email = emails.find((email) => email.primary)?.email || data.email;
|
|
44
66
|
const email_verified = emails.find((email) => email.email === data.email)?.verified ?? false;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"github.mjs","names":[],"sources":["../../../src/oauth2/provider/github.ts"],"sourcesContent":["import { invariant } from '@shware/utils';\nimport { OAuth2Error } from '../error';\nimport type { OAuth2Token, Provider } from '../types';\nimport { createAuthorizationUri, exchangeAuthorizationCode } from './common';\n\nexport function createGithubProvider(): Provider {\n return {\n authorizationUri: 'https://github.com/login/oauth/authorize',\n tokenUri: 'https://github.com/login/oauth/access_token',\n userInfoUri: 'https://api.github.com/user',\n userNameAttribute: 'id',\n defaultScope: ['user:email'],\n createAuthorizationUri({ pkce: _, ...params }) {\n return createAuthorizationUri({\n ...params,\n scope: params.scope ?? this.defaultScope,\n authorizationUri: this.authorizationUri,\n });\n },\n async exchangeAuthorizationCode({ pkce: _, ...params }) {\n const response = await exchangeAuthorizationCode({
|
|
1
|
+
{"version":3,"file":"github.mjs","names":[],"sources":["../../../src/oauth2/provider/github.ts"],"sourcesContent":["import { invariant } from '@shware/utils';\nimport { OAuth2Error } from '../error';\nimport type { OAuth2Token, Provider } from '../types';\nimport { createAuthorizationUri, exchangeAuthorizationCode } from './common';\n\n/**\n * GitHub's REST API rejects any request without a `User-Agent` header with a 403. Node's fetch sends\n * a default one, but Cloudflare Workers' fetch sends none, so every GitHub request sets it explicitly.\n * reference: https://docs.github.com/en/rest/using-the-rest-api/troubleshooting-the-rest-api#user-agent-required\n */\nconst USER_AGENT = '@shware/security';\n\n/** A short slice of an error response body, enough to tell GitHub's failures apart in logs. */\nasync function describeFailure(response: Response, message: string) {\n const body = await response.text().catch(() => '');\n const detail = body ? `: ${body.slice(0, 200)}` : '';\n return `${message} (HTTP ${response.status})${detail}`;\n}\n\nexport function createGithubProvider(): Provider {\n return {\n authorizationUri: 'https://github.com/login/oauth/authorize',\n tokenUri: 'https://github.com/login/oauth/access_token',\n userInfoUri: 'https://api.github.com/user',\n userNameAttribute: 'id',\n defaultScope: ['user:email'],\n createAuthorizationUri({ pkce: _, ...params }) {\n return createAuthorizationUri({\n ...params,\n scope: params.scope ?? this.defaultScope,\n authorizationUri: this.authorizationUri,\n });\n },\n async exchangeAuthorizationCode({ pkce: _, ...params }) {\n const response = await exchangeAuthorizationCode({\n ...params,\n tokenUri: this.tokenUri,\n headers: { 'User-Agent': USER_AGENT },\n });\n if (!response.ok) {\n const { error, error_description } = (await response.json()) as GithubErrorResponse;\n throw new OAuth2Error(response.status, error, error_description);\n }\n // GitHub answers a failed exchange (bad_verification_code, incorrect_client_credentials, ...)\n // with HTTP 200 and an error body, so a 200 alone does not mean a token was issued.\n const body = (await response.json()) as GithubToken & Partial<GithubErrorResponse>;\n if (body.error) throw new OAuth2Error(400, body.error, body.error_description);\n return body;\n },\n async getUserInfo({ access_token }) {\n invariant(access_token, 'access_token is required');\n invariant(this.userInfoUri, 'userInfoUri is required');\n const headers = {\n Accept: 'application/json',\n Authorization: `Bearer ${access_token}`,\n 'User-Agent': USER_AGENT,\n };\n const response = await fetch(this.userInfoUri, { headers });\n if (!response.ok) {\n const message = await describeFailure(response, 'Failed to fetch user info');\n throw new OAuth2Error(response.status, 'invalid_request', message);\n }\n const data = (await response.json()) as GithubUserInfo;\n const emailResponse = await fetch('https://api.github.com/user/emails', { headers });\n if (!emailResponse.ok) {\n const message = await describeFailure(emailResponse, 'Failed to fetch user email');\n throw new OAuth2Error(emailResponse.status, 'invalid_request', message);\n }\n const emails = (await emailResponse.json()) as GithubEmail[];\n data.email = emails.find((email) => email.primary)?.email || data.email;\n const email_verified = emails.find((email) => email.email === data.email)?.verified ?? false;\n return {\n data,\n claims: {\n sub: data.id,\n name: data.name || data.login,\n email_verified,\n email: data.email,\n picture: data.avatar_url,\n profile: data.html_url,\n website: data.html_url,\n updated_at: data.updated_at ? Date.parse(data.updated_at) : undefined,\n },\n };\n },\n };\n}\n\nexport const github = createGithubProvider();\n\nexport interface GithubUserInfo {\n login: string;\n id: string;\n node_id: string;\n avatar_url: string;\n gravatar_id: string;\n url: string;\n html_url: string;\n followers_url: string;\n following_url: string;\n gists_url: string;\n starred_url: string;\n subscriptions_url: string;\n organizations_url: string;\n repos_url: string;\n events_url: string;\n received_events_url: string;\n type: string;\n site_admin: boolean;\n name: string;\n company: string;\n blog: string;\n location: string;\n email: string;\n hireable: boolean;\n bio: string;\n twitter_username: string;\n public_repos: string;\n public_gists: string;\n followers: string;\n following: string;\n created_at: string;\n updated_at: string;\n private_gists: string;\n total_private_repos: string;\n owned_private_repos: string;\n disk_usage: string;\n collaborators: string;\n two_factor_authentication: boolean;\n plan: {\n name: string;\n space: string;\n private_repos: string;\n collaborators: string;\n };\n}\n\ninterface GithubEmail {\n email: string;\n primary: boolean;\n verified: boolean;\n visibility: 'public' | 'private';\n}\n\nexport interface GithubToken extends OAuth2Token {\n access_token: string;\n token_type: string;\n scope: string;\n expires_in: number;\n refresh_token: string;\n}\n\ninterface GithubErrorResponse {\n error: string;\n error_description: string;\n error_uri: string;\n}\n"],"mappings":";;;;;;;;;AAUA,MAAM,aAAa;;AAGnB,eAAe,gBAAgB,UAAoB,SAAiB;CAClE,MAAM,OAAO,MAAM,SAAS,KAAK,CAAC,CAAC,YAAY,EAAE;CACjD,MAAM,SAAS,OAAO,KAAK,KAAK,MAAM,GAAG,GAAG,MAAM;CAClD,OAAO,GAAG,QAAQ,SAAS,SAAS,OAAO,GAAG;AAChD;AAEA,SAAgB,uBAAiC;CAC/C,OAAO;EACL,kBAAkB;EAClB,UAAU;EACV,aAAa;EACb,mBAAmB;EACnB,cAAc,CAAC,YAAY;EAC3B,uBAAuB,EAAE,MAAM,GAAG,GAAG,UAAU;GAC7C,OAAO,uBAAuB;IAC5B,GAAG;IACH,OAAO,OAAO,SAAS,KAAK;IAC5B,kBAAkB,KAAK;GACzB,CAAC;EACH;EACA,MAAM,0BAA0B,EAAE,MAAM,GAAG,GAAG,UAAU;GACtD,MAAM,WAAW,MAAM,0BAA0B;IAC/C,GAAG;IACH,UAAU,KAAK;IACf,SAAS,EAAE,cAAc,WAAW;GACtC,CAAC;GACD,IAAI,CAAC,SAAS,IAAI;IAChB,MAAM,EAAE,OAAO,sBAAuB,MAAM,SAAS,KAAK;IAC1D,MAAM,IAAI,YAAY,SAAS,QAAQ,OAAO,iBAAiB;GACjE;GAGA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|
|
|
256
256
|
await this.expirationStore.cleanupExpiredSessions(cleanupCount);
|
|
257
257
|
}
|
|
258
258
|
};
|
|
259
|
+
const INCREMENT_SCRIPT = `
|
|
260
|
+
local count = redis.call('INCR', KEYS[1])
|
|
261
|
+
if count == 1 then redis.call('EXPIRE', KEYS[1], ARGV[1]) end
|
|
262
|
+
return count
|
|
263
|
+
`;
|
|
259
264
|
var RedisKVRepository = class {
|
|
260
265
|
redis;
|
|
261
266
|
constructor(redis) {
|
|
@@ -271,6 +276,10 @@ var RedisKVRepository = class {
|
|
|
271
276
|
async removeItem(key) {
|
|
272
277
|
await this.redis.del(key);
|
|
273
278
|
}
|
|
279
|
+
async increment(key, expiresIn) {
|
|
280
|
+
const count = await this.redis.eval(INCREMENT_SCRIPT, 1, key, expiresIn);
|
|
281
|
+
return Number(count);
|
|
282
|
+
}
|
|
274
283
|
};
|
|
275
284
|
//#endregion
|
|
276
285
|
exports.RedisIndexedSessionRepository = RedisIndexedSessionRepository;
|
|
@@ -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 this.redis.get(key);\n }\n\n async removeItem(key: string) {\n await this.redis.del(key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2B,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"}
|
|
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\nconst INCREMENT_SCRIPT = `\nlocal count = redis.call('INCR', KEYS[1])\nif count == 1 then redis.call('EXPIRE', KEYS[1], ARGV[1]) end\nreturn count\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 async increment(key: string, expiresIn: number): Promise<number> {\n // INCR and the creating EXPIRE run as one script, so the key never exists without a TTL and\n // an existing key keeps its expiry.\n const count = await this.redis.eval(INCREMENT_SCRIPT, 1, key, expiresIn);\n return Number(count);\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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AO;EAEnC;EACA,OAAO;CACT;CAEA,MAAM,oBAAoB,eAAuB;EAC/C,OAAO,KAAK,6BAA6BC,uBAAAA,2BAA2B,aAAa;CACnF;CAEA,MAAM,uBAAuB,cAAuB;EAClD,MAAM,KAAK,gBAAgB,uBAAuB,YAAY;CAChE;AACF;AAEA,MAAM,mBAAmB;;;;;AAMzB,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;CAEA,MAAM,UAAU,KAAa,WAAoC;EAG/D,MAAM,QAAQ,MAAM,KAAK,MAAM,KAAK,kBAAkB,GAAG,KAAK,SAAS;EACvE,OAAO,OAAO,KAAK;CACrB;AACF"}
|
package/dist/session/redis.d.cts
CHANGED
|
@@ -52,6 +52,7 @@ export declare class RedisKVRepository implements KVRepository {
|
|
|
52
52
|
setItem(key: string, value: string, expiresIn?: number): Promise<void>;
|
|
53
53
|
getItem(key: string): Promise<string | null>;
|
|
54
54
|
removeItem(key: string): Promise<void>;
|
|
55
|
+
increment(key: string, expiresIn: number): Promise<number>;
|
|
55
56
|
}
|
|
56
57
|
//#endregion
|
|
57
58
|
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"redis.d.cts","names":[],"sources":["../../src/session/redis.ts"],"mappings":";;;;cAWM,wBAAwB;mBACX;EAEV;EACA,OAAK;EACL;EACA;EACA;EAEP,YAAY,QAAQ,YAAY;EAiBhC,sBAAsB;EAKtB,oBAAoB;EAKpB;EAIA;EAIA;EAIA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@ export declare class RedisKVRepository implements KVRepository {
|
|
|
52
52
|
setItem(key: string, value: string, expiresIn?: number): Promise<void>;
|
|
53
53
|
getItem(key: string): Promise<string | null>;
|
|
54
54
|
removeItem(key: string): Promise<void>;
|
|
55
|
+
increment(key: string, expiresIn: number): Promise<number>;
|
|
55
56
|
}
|
|
56
57
|
//#endregion
|
|
57
58
|
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"redis.d.mts","names":[],"sources":["../../src/session/redis.ts"],"mappings":";;;;cAWM,wBAAwB;mBACX;EAEV;EACA,OAAK;EACL;EACA;EACA;EAEP,YAAY,QAAQ,YAAY;EAiBhC,sBAAsB;EAKtB,oBAAoB;EAKpB;EAIA;EAIA;EAIA;EAIA;EAIA,uBAAuB;EAKvB;EAIA,aAAa;EAIb;EAIA,aAAa,cAAc;EAK3B,gBAAgB;;qBA6DL,yCAAyC,kBAAkB;mBACrD;mBACA;mBACA;UAET;EAER,YAAY,OAAO,OAAO,YAAW;EAMrC,8BAA8B;UAItB;UAIA;UAIA;UAIA;UAIM;UAyBA;UAgEA;EAuBd,iBAAa;EAMP,KAAK,SAAS,eAAY;EAK1B,SAAS,oBAAoB,QAAQ;EAIrC,WAAW,oBAAiB;EAkB5B,6BAA6B,mBAAmB,qBAAkB,QAAA,YAAA;EAoBlE,oBAAoB,wBAAqB,QAAA,YAAA;EAIzC,uBAAuB,wBAAqB;;
|
|
1
|
+
{"version":3,"file":"redis.d.mts","names":[],"sources":["../../src/session/redis.ts"],"mappings":";;;;cAWM,wBAAwB;mBACX;EAEV;EACA,OAAK;EACL;EACA;EACA;EAEP,YAAY,QAAQ,YAAY;EAiBhC,sBAAsB;EAKtB,oBAAoB;EAKpB;EAIA;EAIA;EAIA;EAIA;EAIA,uBAAuB;EAKvB;EAIA,aAAa;EAIb;EAIA,aAAa,cAAc;EAK3B,gBAAgB;;qBA6DL,yCAAyC,kBAAkB;mBACrD;mBACA;mBACA;UAET;EAER,YAAY,OAAO,OAAO,YAAW;EAMrC,8BAA8B;UAItB;UAIA;UAIA;UAIA;UAIM;UAyBA;UAgEA;EAuBd,iBAAa;EAMP,KAAK,SAAS,eAAY;EAK1B,SAAS,oBAAoB,QAAQ;EAIrC,WAAW,oBAAiB;EAkB5B,6BAA6B,mBAAmB,qBAAkB,QAAA,YAAA;EAoBlE,oBAAoB,wBAAqB,QAAA,YAAA;EAIzC,uBAAuB,wBAAqB;;qBAWvC,6BAA6B;mBACvB;EAEjB,YAAY,OAAO;EAIb,QAAQ,aAAa,eAAe,qBAAkB;EAQtD,QAAQ,cAAc;EAItB,WAAW,cAAW;EAItB,UAAU,aAAa,oBAAoB"}
|
package/dist/session/redis.mjs
CHANGED
|
@@ -255,6 +255,11 @@ var RedisIndexedSessionRepository = class {
|
|
|
255
255
|
await this.expirationStore.cleanupExpiredSessions(cleanupCount);
|
|
256
256
|
}
|
|
257
257
|
};
|
|
258
|
+
const INCREMENT_SCRIPT = `
|
|
259
|
+
local count = redis.call('INCR', KEYS[1])
|
|
260
|
+
if count == 1 then redis.call('EXPIRE', KEYS[1], ARGV[1]) end
|
|
261
|
+
return count
|
|
262
|
+
`;
|
|
258
263
|
var RedisKVRepository = class {
|
|
259
264
|
redis;
|
|
260
265
|
constructor(redis) {
|
|
@@ -270,6 +275,10 @@ var RedisKVRepository = class {
|
|
|
270
275
|
async removeItem(key) {
|
|
271
276
|
await this.redis.del(key);
|
|
272
277
|
}
|
|
278
|
+
async increment(key, expiresIn) {
|
|
279
|
+
const count = await this.redis.eval(INCREMENT_SCRIPT, 1, key, expiresIn);
|
|
280
|
+
return Number(count);
|
|
281
|
+
}
|
|
273
282
|
};
|
|
274
283
|
//#endregion
|
|
275
284
|
export { RedisIndexedSessionRepository, RedisKVRepository };
|
|
@@ -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 this.redis.get(key);\n }\n\n async removeItem(key: string) {\n await this.redis.del(key);\n }\n}\n"],"mappings":";;;AAKA,MAAM,oBAAoB;AAC1B,MAAM,yBAAyB;AAC/B,MAAM,4BAA4B;AAClC,MAAM,mBAAmB;AACzB,MAAM,yBAAyB;AAE/B,IAAM,eAAN,MAAsC;CACpC;CAEA;CACA,wBAAe,IAAI,IAAoC;CACvD;CACA;CACA,yBAA+C;CAE/C,YAAY,QAAoB,OAAgB;EAC9C,KAAK,SAAS;EACd,KAAK,QAAQ;EACb,KAAK,oBAAoB,OAAO,MAAM;EACtC,KAAK,wBAAwB,kBAAkB,IAAI;EAEnD,IAAI,OAAO;GACT,KAAK,MAAM,IAAI,mBAAmB,OAAO,gBAAgB,CAAC;GAC1D,KAAK,MAAM,IAAI,wBAAwB,OAAO,oBAAoB,CAAC;GACnE,KAAK,MAAM,IAAI,2BAA2B,OAAO,uBAAuB,CAAC;GACzE,KAAK,OAAO,kBAAkB,CAAC,CAAC,SAAS,SAAS;IAChD,MAAM,QAAQ,KAAK,OAAO,aAAa,IAAI;IAC3C,IAAI,OAAO,KAAK,MAAM,IAAI,KAAK,sBAAsB,IAAI,GAAG,KAAK;GACnE,CAAC;EACH;CACF;CAEA,sBAAsB,MAAc;EAClC,OAAO,mBAAmB;CAC5B;CAGA,oBAAoB,kBAA0B;EAC5C,KAAK,OAAO,oBAAoB,gBAAgB;EAChD,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Aa,MAAM,KAAK,MAAM,SAAS,YAAY;EACzD,IAAI,WAAW,WAAW,GACxB,uBAAO,IAAI,IAA0B;EAEvC,MAAM,2BAAW,IAAI,IAA0B;EAC/C,KAAK,MAAM,aAAa,YAAY;GAClC,MAAM,UAAU,MAAM,KAAK,SAAS,SAAS;GAC7C,IAAI,YAAY,MACd,SAAS,IAAI,WAAW,OAAO;EAEnC;EACA,OAAO;CACT;CAEA,MAAM,oBAAoB,eAAuB;EAC/C,OAAO,KAAK,6BAA6B,2BAA2B,aAAa;CACnF;CAEA,MAAM,uBAAuB,cAAuB;EAClD,MAAM,KAAK,gBAAgB,uBAAuB,YAAY;CAChE;AACF;AAEA,IAAa,oBAAb,MAAuD;CACrD;CAEA,YAAY,OAAc;EACxB,KAAK,QAAQ;CACf;CAEA,MAAM,QAAQ,KAAa,OAAe,WAAoB;EAC5D,IAAI,WACF,MAAM,KAAK,MAAM,IAAI,KAAK,OAAO,MAAM,SAAS;OAEhD,MAAM,KAAK,MAAM,IAAI,KAAK,KAAK;CAEnC;CAEA,MAAM,QAAQ,KAAqC;EACjD,OAAO,KAAK,MAAM,IAAI,GAAG;CAC3B;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\nconst INCREMENT_SCRIPT = `\nlocal count = redis.call('INCR', KEYS[1])\nif count == 1 then redis.call('EXPIRE', KEYS[1], ARGV[1]) end\nreturn count\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 async increment(key: string, expiresIn: number): Promise<number> {\n // INCR and the creating EXPIRE run as one script, so the key never exists without a TTL and\n // an existing key keeps its expiry.\n const count = await this.redis.eval(INCREMENT_SCRIPT, 1, key, expiresIn);\n return Number(count);\n }\n}\n"],"mappings":";;;AAKA,MAAM,oBAAoB;AAC1B,MAAM,yBAAyB;AAC/B,MAAM,4BAA4B;AAClC,MAAM,mBAAmB;AACzB,MAAM,yBAAyB;AAE/B,IAAM,eAAN,MAAsC;CACpC;CAEA;CACA,wBAAe,IAAI,IAAoC;CACvD;CACA;CACA,yBAA+C;CAE/C,YAAY,QAAoB,OAAgB;EAC9C,KAAK,SAAS;EACd,KAAK,QAAQ;EACb,KAAK,oBAAoB,OAAO,MAAM;EACtC,KAAK,wBAAwB,kBAAkB,IAAI;EAEnD,IAAI,OAAO;GACT,KAAK,MAAM,IAAI,mBAAmB,OAAO,gBAAgB,CAAC;GAC1D,KAAK,MAAM,IAAI,wBAAwB,OAAO,oBAAoB,CAAC;GACnE,KAAK,MAAM,IAAI,2BAA2B,OAAO,uBAAuB,CAAC;GACzE,KAAK,OAAO,kBAAkB,CAAC,CAAC,SAAS,SAAS;IAChD,MAAM,QAAQ,KAAK,OAAO,aAAa,IAAI;IAC3C,IAAI,OAAO,KAAK,MAAM,IAAI,KAAK,sBAAsB,IAAI,GAAG,KAAK;GACnE,CAAC;EACH;CACF;CAEA,sBAAsB,MAAc;EAClC,OAAO,mBAAmB;CAC5B;CAGA,oBAAoB,kBAA0B;EAC5C,KAAK,OAAO,oBAAoB,gBAAgB;EAChD,KAAK,MAAM,IAAI,wBAAwB,gBAAgB;CACzD;CAEA,YAAY;EACV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,GACxB,uBAAO,IAAI,IAA0B;EAEvC,MAAM,2BAAW,IAAI,IAA0B;EAC/C,KAAK,MAAM,aAAa,YAAY;GAClC,MAAM,UAAU,MAAM,KAAK,SAAS,SAAS;GAC7C,IAAI,YAAY,MACd,SAAS,IAAI,WAAW,OAAO;EAEnC;EACA,OAAO;CACT;CAEA,MAAM,oBAAoB,eAAuB;EAC/C,OAAO,KAAK,6BAA6B,2BAA2B,aAAa;CACnF;CAEA,MAAM,uBAAuB,cAAuB;EAClD,MAAM,KAAK,gBAAgB,uBAAuB,YAAY;CAChE;AACF;AAEA,MAAM,mBAAmB;;;;;AAMzB,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;CAEA,MAAM,UAAU,KAAa,WAAoC;EAG/D,MAAM,QAAQ,MAAM,KAAK,MAAM,KAAK,kBAAkB,GAAG,KAAK,SAAS;EACvE,OAAO,OAAO,KAAK;CACrB;AACF"}
|
package/dist/session/types.d.cts
CHANGED
|
@@ -35,10 +35,21 @@ export interface SessionRepository<S extends Session = Session> {
|
|
|
35
35
|
findByPrincipalName(principalName: string): Promise<Map<string, S>>;
|
|
36
36
|
cleanupExpiredSessions(cleanupCount?: number): Promise<void>;
|
|
37
37
|
}
|
|
38
|
+
/**
|
|
39
|
+
* Short-lived values: OAuth2 state/nonce, verification codes and their counters, desktop codes.
|
|
40
|
+
* `expiresIn` is in seconds; an expired key must read as absent.
|
|
41
|
+
*/
|
|
38
42
|
export interface KVRepository {
|
|
39
43
|
setItem(key: string, value: string, expiresIn?: number): Promise<void>;
|
|
40
44
|
getItem(key: string): Promise<string | null>;
|
|
41
45
|
removeItem(key: string): Promise<void>;
|
|
46
|
+
/**
|
|
47
|
+
* Atomically increments the integer counter at `key` and returns the new count. An absent or
|
|
48
|
+
* expired key starts over at 1 and expires in `expiresIn` seconds; an existing key keeps its
|
|
49
|
+
* expiry. Must be atomic under concurrent calls: verification attempt limits rely on every
|
|
50
|
+
* caller seeing a distinct count.
|
|
51
|
+
*/
|
|
52
|
+
increment(key: string, expiresIn: number): Promise<number>;
|
|
42
53
|
}
|
|
43
54
|
//#endregion
|
|
44
55
|
//# sourceMappingURL=types.d.cts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.cts","names":[],"sources":["../../src/session/types.ts"],"mappings":";;iBAEiB,uBAAuB;EACtC;EACA,YAAY;EACZ;EACA;EACA;;iBAGe;EACf;EACA,iBAAiB;;YAGP;iBAGK;EACf;EACA;EAEA,aAAa;EACb;EACA,aAAa,cAAc;EAC3B,gBAAgB;EAEhB;EACA;EACA,oBAAoB;EAEpB;EACA,uBAAuB;EAEvB;;iBAGe,kBAAkB,UAAU,UAAU;EACrD,iBAAiB;EACjB,KAAK,SAAS,IAAI;EAClB,SAAS,oBAAoB,QAAQ;EACrC,WAAW,oBAAoB;EAG/B,6BAA6B,mBAAmB,qBAAqB,QAAQ,YAAY;EACzF,oBAAoB,wBAAwB,QAAQ,YAAY;EAGhE,uBAAuB,wBAAwB
|
|
1
|
+
{"version":3,"file":"types.d.cts","names":[],"sources":["../../src/session/types.ts"],"mappings":";;iBAEiB,uBAAuB;EACtC;EACA,YAAY;EACZ;EACA;EACA;;iBAGe;EACf;EACA,iBAAiB;;YAGP;iBAGK;EACf;EACA;EAEA,aAAa;EACb;EACA,aAAa,cAAc;EAC3B,gBAAgB;EAEhB;EACA;EACA,oBAAoB;EAEpB;EACA,uBAAuB;EAEvB;;iBAGe,kBAAkB,UAAU,UAAU;EACrD,iBAAiB;EACjB,KAAK,SAAS,IAAI;EAClB,SAAS,oBAAoB,QAAQ;EACrC,WAAW,oBAAoB;EAG/B,6BAA6B,mBAAmB,qBAAqB,QAAQ,YAAY;EACzF,oBAAoB,wBAAwB,QAAQ,YAAY;EAGhE,uBAAuB,wBAAwB;;;;;;iBAOhC;EACf,QAAQ,aAAa,eAAe,qBAAqB;EACzD,QAAQ,cAAc;EACtB,WAAW,cAAc;;;;;;;EAOzB,UAAU,aAAa,oBAAoB"}
|
package/dist/session/types.d.mts
CHANGED
|
@@ -35,10 +35,21 @@ export interface SessionRepository<S extends Session = Session> {
|
|
|
35
35
|
findByPrincipalName(principalName: string): Promise<Map<string, S>>;
|
|
36
36
|
cleanupExpiredSessions(cleanupCount?: number): Promise<void>;
|
|
37
37
|
}
|
|
38
|
+
/**
|
|
39
|
+
* Short-lived values: OAuth2 state/nonce, verification codes and their counters, desktop codes.
|
|
40
|
+
* `expiresIn` is in seconds; an expired key must read as absent.
|
|
41
|
+
*/
|
|
38
42
|
export interface KVRepository {
|
|
39
43
|
setItem(key: string, value: string, expiresIn?: number): Promise<void>;
|
|
40
44
|
getItem(key: string): Promise<string | null>;
|
|
41
45
|
removeItem(key: string): Promise<void>;
|
|
46
|
+
/**
|
|
47
|
+
* Atomically increments the integer counter at `key` and returns the new count. An absent or
|
|
48
|
+
* expired key starts over at 1 and expires in `expiresIn` seconds; an existing key keeps its
|
|
49
|
+
* expiry. Must be atomic under concurrent calls: verification attempt limits rely on every
|
|
50
|
+
* caller seeing a distinct count.
|
|
51
|
+
*/
|
|
52
|
+
increment(key: string, expiresIn: number): Promise<number>;
|
|
42
53
|
}
|
|
43
54
|
//#endregion
|
|
44
55
|
//# sourceMappingURL=types.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.mts","names":[],"sources":["../../src/session/types.ts"],"mappings":";;iBAEiB,uBAAuB;EACtC;EACA,YAAY;EACZ;EACA;EACA;;iBAGe;EACf;EACA,iBAAiB;;YAGP;iBAGK;EACf;EACA;EAEA,aAAa;EACb;EACA,aAAa,cAAc;EAC3B,gBAAgB;EAEhB;EACA;EACA,oBAAoB;EAEpB;EACA,uBAAuB;EAEvB;;iBAGe,kBAAkB,UAAU,UAAU;EACrD,iBAAiB;EACjB,KAAK,SAAS,IAAI;EAClB,SAAS,oBAAoB,QAAQ;EACrC,WAAW,oBAAoB;EAG/B,6BAA6B,mBAAmB,qBAAqB,QAAQ,YAAY;EACzF,oBAAoB,wBAAwB,QAAQ,YAAY;EAGhE,uBAAuB,wBAAwB
|
|
1
|
+
{"version":3,"file":"types.d.mts","names":[],"sources":["../../src/session/types.ts"],"mappings":";;iBAEiB,uBAAuB;EACtC;EACA,YAAY;EACZ;EACA;EACA;;iBAGe;EACf;EACA,iBAAiB;;YAGP;iBAGK;EACf;EACA;EAEA,aAAa;EACb;EACA,aAAa,cAAc;EAC3B,gBAAgB;EAEhB;EACA;EACA,oBAAoB;EAEpB;EACA,uBAAuB;EAEvB;;iBAGe,kBAAkB,UAAU,UAAU;EACrD,iBAAiB;EACjB,KAAK,SAAS,IAAI;EAClB,SAAS,oBAAoB,QAAQ;EACrC,WAAW,oBAAoB;EAG/B,6BAA6B,mBAAmB,qBAAqB,QAAQ,YAAY;EACzF,oBAAoB,wBAAwB,QAAQ,YAAY;EAGhE,uBAAuB,wBAAwB;;;;;;iBAOhC;EACf,QAAQ,aAAa,eAAe,qBAAqB;EACzD,QAAQ,cAAc;EACtB,WAAW,cAAc;;;;;;;EAOzB,UAAU,aAAa,oBAAoB"}
|
package/dist/utils/valid.cjs
CHANGED
|
@@ -11,6 +11,17 @@ function invalidArgument(reason) {
|
|
|
11
11
|
}]
|
|
12
12
|
} };
|
|
13
13
|
}
|
|
14
|
+
function resourceExhausted(reason, message) {
|
|
15
|
+
return { error: {
|
|
16
|
+
code: 429,
|
|
17
|
+
status: "RESOURCE_EXHAUSTED",
|
|
18
|
+
message,
|
|
19
|
+
details: [{
|
|
20
|
+
"@type": "type.googleapis.com/google.rpc.ErrorInfo",
|
|
21
|
+
reason
|
|
22
|
+
}]
|
|
23
|
+
} };
|
|
24
|
+
}
|
|
14
25
|
function valid(schema, json) {
|
|
15
26
|
const result = schema.safeParse(json);
|
|
16
27
|
if (result.success) return {
|
|
@@ -51,6 +62,7 @@ async function verifyTurnstileToken(secret, token) {
|
|
|
51
62
|
}
|
|
52
63
|
//#endregion
|
|
53
64
|
exports.invalidArgument = invalidArgument;
|
|
65
|
+
exports.resourceExhausted = resourceExhausted;
|
|
54
66
|
exports.valid = valid;
|
|
55
67
|
exports.verifyTurnstileToken = verifyTurnstileToken;
|
|
56
68
|
|
package/dist/utils/valid.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"valid.cjs","names":[],"sources":["../../src/utils/valid.ts"],"sourcesContent":["import type { ZodType, output } from 'zod';\nimport type { ZodMiniType, output as outputMini } from 'zod/mini';\n\ntype ErrorBody = {\n error: {\n code: number;\n status: string;\n message: string;\n details: unknown[];\n };\n};\n\nexport function invalidArgument(reason: string): ErrorBody {\n return {\n error: {\n code: 400,\n status: 'INVALID_ARGUMENT',\n message: 'Invalid verification code',\n details: [{ '@type': 'type.googleapis.com/google.rpc.ErrorInfo', reason }],\n },\n };\n}\n\ntype Result<S extends ZodType | ZodMiniType> =\n | { error: null; data: S extends ZodType ? output<S> : outputMini<S> }\n | { error: ErrorBody; data: null };\n\nexport function valid<S extends ZodType | ZodMiniType>(schema: S, json: unknown): Result<S> {\n const result = schema.safeParse(json);\n if (result.success) {\n return {\n error: null,\n data: result.data as S extends ZodType ? output<S> : outputMini<S>,\n };\n }\n\n const fieldViolations = result.error.issues.map(({ code, path, message }) => ({\n field: path.join('.'),\n description: message,\n reason: code.toUpperCase(),\n localizedMessage: { locale: 'en-US', message },\n }));\n\n const error = {\n error: {\n code: 400,\n status: 'INVALID_ARGUMENT',\n message: 'Invalid request',\n details: [{ '@type': 'type.googleapis.com/google.rpc.BadRequest', fieldViolations }],\n },\n };\n\n return { error, data: null };\n}\n\nexport async function verifyTurnstileToken(secret: string, token: string) {\n const response = await fetch('https://challenges.cloudflare.com/turnstile/v0/siteverify', {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({ secret, response: token }),\n });\n\n const data = (await response.json()) as { success: boolean };\n if (data.success) return { error: null };\n return { error: invalidArgument('TURNSTILE_VERIFICATION_FAILED') };\n}\n"],"mappings":";;AAYA,SAAgB,gBAAgB,QAA2B;CACzD,OAAO,EACL,OAAO;EACL,MAAM;EACN,QAAQ;EACR,SAAS;EACT,SAAS,CAAC;GAAE,SAAS;GAA4C;EAAO,CAAC;CAC3E,EACF;AACF;AAMA,SAAgB,MAAuC,QAAW,MAA0B;CAC1F,MAAM,SAAS,OAAO,UAAU,IAAI;CACpC,IAAI,OAAO,SACT,OAAO;EACL,OAAO;EACP,MAAM,OAAO;CACf;CAmBF,OAAO;EAAE,OAAA,EARP,OAAO;GACL,MAAM;GACN,QAAQ;GACR,SAAS;GACT,SAAS,CAAC;IAAE,SAAS;IAA6C,iBAZ9C,OAAO,MAAM,OAAO,KAAK,EAAE,MAAM,MAAM,eAAe;KAC5E,OAAO,KAAK,KAAK,GAAG;KACpB,aAAa;KACb,QAAQ,KAAK,YAAY;KACzB,kBAAkB;MAAE,QAAQ;MAAS;KAAQ;IAC/C,EAOoF;GAAE,CAAC;EACrF,EAGW;EAAG,MAAM;CAAK;AAC7B;AAEA,eAAsB,qBAAqB,QAAgB,OAAe;CAQxE,KAAI,OADgB,MANG,MAAM,6DAA6D;EACxF,QAAQ;EACR,SAAS,EAAE,gBAAgB,oCAAoC;EAC/D,MAAM,IAAI,gBAAgB;GAAE;GAAQ,UAAU;EAAM,CAAC;CACvD,CAAC,EAAA,CAE4B,KAAK,EAAA,CACzB,SAAS,OAAO,EAAE,OAAO,KAAK;CACvC,OAAO,EAAE,OAAO,gBAAgB,+BAA+B,EAAE;AACnE"}
|
|
1
|
+
{"version":3,"file":"valid.cjs","names":[],"sources":["../../src/utils/valid.ts"],"sourcesContent":["import type { ZodType, output } from 'zod';\nimport type { ZodMiniType, output as outputMini } from 'zod/mini';\n\ntype ErrorBody = {\n error: {\n code: number;\n status: string;\n message: string;\n details: unknown[];\n };\n};\n\nexport function invalidArgument(reason: string): ErrorBody {\n return {\n error: {\n code: 400,\n status: 'INVALID_ARGUMENT',\n message: 'Invalid verification code',\n details: [{ '@type': 'type.googleapis.com/google.rpc.ErrorInfo', reason }],\n },\n };\n}\n\nexport function resourceExhausted(reason: string, message: string): ErrorBody {\n return {\n error: {\n code: 429,\n status: 'RESOURCE_EXHAUSTED',\n message,\n details: [{ '@type': 'type.googleapis.com/google.rpc.ErrorInfo', reason }],\n },\n };\n}\n\ntype Result<S extends ZodType | ZodMiniType> =\n | { error: null; data: S extends ZodType ? output<S> : outputMini<S> }\n | { error: ErrorBody; data: null };\n\nexport function valid<S extends ZodType | ZodMiniType>(schema: S, json: unknown): Result<S> {\n const result = schema.safeParse(json);\n if (result.success) {\n return {\n error: null,\n data: result.data as S extends ZodType ? output<S> : outputMini<S>,\n };\n }\n\n const fieldViolations = result.error.issues.map(({ code, path, message }) => ({\n field: path.join('.'),\n description: message,\n reason: code.toUpperCase(),\n localizedMessage: { locale: 'en-US', message },\n }));\n\n const error = {\n error: {\n code: 400,\n status: 'INVALID_ARGUMENT',\n message: 'Invalid request',\n details: [{ '@type': 'type.googleapis.com/google.rpc.BadRequest', fieldViolations }],\n },\n };\n\n return { error, data: null };\n}\n\nexport async function verifyTurnstileToken(secret: string, token: string) {\n const response = await fetch('https://challenges.cloudflare.com/turnstile/v0/siteverify', {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({ secret, response: token }),\n });\n\n const data = (await response.json()) as { success: boolean };\n if (data.success) return { error: null };\n return { error: invalidArgument('TURNSTILE_VERIFICATION_FAILED') };\n}\n"],"mappings":";;AAYA,SAAgB,gBAAgB,QAA2B;CACzD,OAAO,EACL,OAAO;EACL,MAAM;EACN,QAAQ;EACR,SAAS;EACT,SAAS,CAAC;GAAE,SAAS;GAA4C;EAAO,CAAC;CAC3E,EACF;AACF;AAEA,SAAgB,kBAAkB,QAAgB,SAA4B;CAC5E,OAAO,EACL,OAAO;EACL,MAAM;EACN,QAAQ;EACR;EACA,SAAS,CAAC;GAAE,SAAS;GAA4C;EAAO,CAAC;CAC3E,EACF;AACF;AAMA,SAAgB,MAAuC,QAAW,MAA0B;CAC1F,MAAM,SAAS,OAAO,UAAU,IAAI;CACpC,IAAI,OAAO,SACT,OAAO;EACL,OAAO;EACP,MAAM,OAAO;CACf;CAmBF,OAAO;EAAE,OAAA,EARP,OAAO;GACL,MAAM;GACN,QAAQ;GACR,SAAS;GACT,SAAS,CAAC;IAAE,SAAS;IAA6C,iBAZ9C,OAAO,MAAM,OAAO,KAAK,EAAE,MAAM,MAAM,eAAe;KAC5E,OAAO,KAAK,KAAK,GAAG;KACpB,aAAa;KACb,QAAQ,KAAK,YAAY;KACzB,kBAAkB;MAAE,QAAQ;MAAS;KAAQ;IAC/C,EAOoF;GAAE,CAAC;EACrF,EAGW;EAAG,MAAM;CAAK;AAC7B;AAEA,eAAsB,qBAAqB,QAAgB,OAAe;CAQxE,KAAI,OADgB,MANG,MAAM,6DAA6D;EACxF,QAAQ;EACR,SAAS,EAAE,gBAAgB,oCAAoC;EAC/D,MAAM,IAAI,gBAAgB;GAAE;GAAQ,UAAU;EAAM,CAAC;CACvD,CAAC,EAAA,CAE4B,KAAK,EAAA,CACzB,SAAS,OAAO,EAAE,OAAO,KAAK;CACvC,OAAO,EAAE,OAAO,gBAAgB,+BAA+B,EAAE;AACnE"}
|
package/dist/utils/valid.d.cts
CHANGED
|
@@ -10,6 +10,7 @@ type ErrorBody = {
|
|
|
10
10
|
};
|
|
11
11
|
};
|
|
12
12
|
export declare function invalidArgument(reason: string): ErrorBody;
|
|
13
|
+
export declare function resourceExhausted(reason: string, message: string): ErrorBody;
|
|
13
14
|
type Result<S extends ZodType | ZodMiniType> = {
|
|
14
15
|
error: null;
|
|
15
16
|
data: S extends ZodType ? output<S> : output$1<S>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"valid.d.cts","names":["outputMini"],"sources":["../../src/utils/valid.ts"],"mappings":";;;KAGK;EACH;IACE;IACA;IACA;IACA;;;wBAIY,gBAAgB,iBAAiB;
|
|
1
|
+
{"version":3,"file":"valid.d.cts","names":["outputMini"],"sources":["../../src/utils/valid.ts"],"mappings":";;;KAGK;EACH;IACE;IACA;IACA;IACA;;;wBAIY,gBAAgB,iBAAiB;wBAWjC,kBAAkB,gBAAgB,kBAAkB;KAW/D,OAAO,UAAU,UAAU;EAC1B;EAAa,MAAM,UAAU,UAAU,OAAO,KAAKA,SAAW;;EAC9D,OAAO;EAAW;;wBAER,MAAM,UAAU,UAAU,aAAa,QAAQ,GAAG,gBAAgB,OAAO;wBA4BnE,qBAAqB,gBAAgB,gBAAa"}
|
package/dist/utils/valid.d.mts
CHANGED
|
@@ -10,6 +10,7 @@ type ErrorBody = {
|
|
|
10
10
|
};
|
|
11
11
|
};
|
|
12
12
|
export declare function invalidArgument(reason: string): ErrorBody;
|
|
13
|
+
export declare function resourceExhausted(reason: string, message: string): ErrorBody;
|
|
13
14
|
type Result<S extends ZodType | ZodMiniType> = {
|
|
14
15
|
error: null;
|
|
15
16
|
data: S extends ZodType ? output$1<S> : output<S>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"valid.d.mts","names":["output","outputMini"],"sources":["../../src/utils/valid.ts"],"mappings":";;;KAGK;EACH;IACE;IACA;IACA;IACA;;;wBAIY,gBAAgB,iBAAiB;
|
|
1
|
+
{"version":3,"file":"valid.d.mts","names":["output","outputMini"],"sources":["../../src/utils/valid.ts"],"mappings":";;;KAGK;EACH;IACE;IACA;IACA;IACA;;;wBAIY,gBAAgB,iBAAiB;wBAWjC,kBAAkB,gBAAgB,kBAAkB;KAW/D,OAAO,UAAU,UAAU;EAC1B;EAAa,MAAM,UAAU,UAAUA,SAAO,KAAKC,OAAW;;EAC9D,OAAO;EAAW;;wBAER,MAAM,UAAU,UAAU,aAAa,QAAQ,GAAG,gBAAgB,OAAO;wBA4BnE,qBAAqB,gBAAgB,gBAAa"}
|
package/dist/utils/valid.mjs
CHANGED
|
@@ -10,6 +10,17 @@ function invalidArgument(reason) {
|
|
|
10
10
|
}]
|
|
11
11
|
} };
|
|
12
12
|
}
|
|
13
|
+
function resourceExhausted(reason, message) {
|
|
14
|
+
return { error: {
|
|
15
|
+
code: 429,
|
|
16
|
+
status: "RESOURCE_EXHAUSTED",
|
|
17
|
+
message,
|
|
18
|
+
details: [{
|
|
19
|
+
"@type": "type.googleapis.com/google.rpc.ErrorInfo",
|
|
20
|
+
reason
|
|
21
|
+
}]
|
|
22
|
+
} };
|
|
23
|
+
}
|
|
13
24
|
function valid(schema, json) {
|
|
14
25
|
const result = schema.safeParse(json);
|
|
15
26
|
if (result.success) return {
|
|
@@ -49,6 +60,6 @@ async function verifyTurnstileToken(secret, token) {
|
|
|
49
60
|
return { error: invalidArgument("TURNSTILE_VERIFICATION_FAILED") };
|
|
50
61
|
}
|
|
51
62
|
//#endregion
|
|
52
|
-
export { invalidArgument, valid, verifyTurnstileToken };
|
|
63
|
+
export { invalidArgument, resourceExhausted, valid, verifyTurnstileToken };
|
|
53
64
|
|
|
54
65
|
//# sourceMappingURL=valid.mjs.map
|
package/dist/utils/valid.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"valid.mjs","names":[],"sources":["../../src/utils/valid.ts"],"sourcesContent":["import type { ZodType, output } from 'zod';\nimport type { ZodMiniType, output as outputMini } from 'zod/mini';\n\ntype ErrorBody = {\n error: {\n code: number;\n status: string;\n message: string;\n details: unknown[];\n };\n};\n\nexport function invalidArgument(reason: string): ErrorBody {\n return {\n error: {\n code: 400,\n status: 'INVALID_ARGUMENT',\n message: 'Invalid verification code',\n details: [{ '@type': 'type.googleapis.com/google.rpc.ErrorInfo', reason }],\n },\n };\n}\n\ntype Result<S extends ZodType | ZodMiniType> =\n | { error: null; data: S extends ZodType ? output<S> : outputMini<S> }\n | { error: ErrorBody; data: null };\n\nexport function valid<S extends ZodType | ZodMiniType>(schema: S, json: unknown): Result<S> {\n const result = schema.safeParse(json);\n if (result.success) {\n return {\n error: null,\n data: result.data as S extends ZodType ? output<S> : outputMini<S>,\n };\n }\n\n const fieldViolations = result.error.issues.map(({ code, path, message }) => ({\n field: path.join('.'),\n description: message,\n reason: code.toUpperCase(),\n localizedMessage: { locale: 'en-US', message },\n }));\n\n const error = {\n error: {\n code: 400,\n status: 'INVALID_ARGUMENT',\n message: 'Invalid request',\n details: [{ '@type': 'type.googleapis.com/google.rpc.BadRequest', fieldViolations }],\n },\n };\n\n return { error, data: null };\n}\n\nexport async function verifyTurnstileToken(secret: string, token: string) {\n const response = await fetch('https://challenges.cloudflare.com/turnstile/v0/siteverify', {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({ secret, response: token }),\n });\n\n const data = (await response.json()) as { success: boolean };\n if (data.success) return { error: null };\n return { error: invalidArgument('TURNSTILE_VERIFICATION_FAILED') };\n}\n"],"mappings":";AAYA,SAAgB,gBAAgB,QAA2B;CACzD,OAAO,EACL,OAAO;EACL,MAAM;EACN,QAAQ;EACR,SAAS;EACT,SAAS,CAAC;GAAE,SAAS;GAA4C;EAAO,CAAC;CAC3E,EACF;AACF;AAMA,SAAgB,MAAuC,QAAW,MAA0B;CAC1F,MAAM,SAAS,OAAO,UAAU,IAAI;CACpC,IAAI,OAAO,SACT,OAAO;EACL,OAAO;EACP,MAAM,OAAO;CACf;CAmBF,OAAO;EAAE,OAAA,EARP,OAAO;GACL,MAAM;GACN,QAAQ;GACR,SAAS;GACT,SAAS,CAAC;IAAE,SAAS;IAA6C,iBAZ9C,OAAO,MAAM,OAAO,KAAK,EAAE,MAAM,MAAM,eAAe;KAC5E,OAAO,KAAK,KAAK,GAAG;KACpB,aAAa;KACb,QAAQ,KAAK,YAAY;KACzB,kBAAkB;MAAE,QAAQ;MAAS;KAAQ;IAC/C,EAOoF;GAAE,CAAC;EACrF,EAGW;EAAG,MAAM;CAAK;AAC7B;AAEA,eAAsB,qBAAqB,QAAgB,OAAe;CAQxE,KAAI,OADgB,MANG,MAAM,6DAA6D;EACxF,QAAQ;EACR,SAAS,EAAE,gBAAgB,oCAAoC;EAC/D,MAAM,IAAI,gBAAgB;GAAE;GAAQ,UAAU;EAAM,CAAC;CACvD,CAAC,EAAA,CAE4B,KAAK,EAAA,CACzB,SAAS,OAAO,EAAE,OAAO,KAAK;CACvC,OAAO,EAAE,OAAO,gBAAgB,+BAA+B,EAAE;AACnE"}
|
|
1
|
+
{"version":3,"file":"valid.mjs","names":[],"sources":["../../src/utils/valid.ts"],"sourcesContent":["import type { ZodType, output } from 'zod';\nimport type { ZodMiniType, output as outputMini } from 'zod/mini';\n\ntype ErrorBody = {\n error: {\n code: number;\n status: string;\n message: string;\n details: unknown[];\n };\n};\n\nexport function invalidArgument(reason: string): ErrorBody {\n return {\n error: {\n code: 400,\n status: 'INVALID_ARGUMENT',\n message: 'Invalid verification code',\n details: [{ '@type': 'type.googleapis.com/google.rpc.ErrorInfo', reason }],\n },\n };\n}\n\nexport function resourceExhausted(reason: string, message: string): ErrorBody {\n return {\n error: {\n code: 429,\n status: 'RESOURCE_EXHAUSTED',\n message,\n details: [{ '@type': 'type.googleapis.com/google.rpc.ErrorInfo', reason }],\n },\n };\n}\n\ntype Result<S extends ZodType | ZodMiniType> =\n | { error: null; data: S extends ZodType ? output<S> : outputMini<S> }\n | { error: ErrorBody; data: null };\n\nexport function valid<S extends ZodType | ZodMiniType>(schema: S, json: unknown): Result<S> {\n const result = schema.safeParse(json);\n if (result.success) {\n return {\n error: null,\n data: result.data as S extends ZodType ? output<S> : outputMini<S>,\n };\n }\n\n const fieldViolations = result.error.issues.map(({ code, path, message }) => ({\n field: path.join('.'),\n description: message,\n reason: code.toUpperCase(),\n localizedMessage: { locale: 'en-US', message },\n }));\n\n const error = {\n error: {\n code: 400,\n status: 'INVALID_ARGUMENT',\n message: 'Invalid request',\n details: [{ '@type': 'type.googleapis.com/google.rpc.BadRequest', fieldViolations }],\n },\n };\n\n return { error, data: null };\n}\n\nexport async function verifyTurnstileToken(secret: string, token: string) {\n const response = await fetch('https://challenges.cloudflare.com/turnstile/v0/siteverify', {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({ secret, response: token }),\n });\n\n const data = (await response.json()) as { success: boolean };\n if (data.success) return { error: null };\n return { error: invalidArgument('TURNSTILE_VERIFICATION_FAILED') };\n}\n"],"mappings":";AAYA,SAAgB,gBAAgB,QAA2B;CACzD,OAAO,EACL,OAAO;EACL,MAAM;EACN,QAAQ;EACR,SAAS;EACT,SAAS,CAAC;GAAE,SAAS;GAA4C;EAAO,CAAC;CAC3E,EACF;AACF;AAEA,SAAgB,kBAAkB,QAAgB,SAA4B;CAC5E,OAAO,EACL,OAAO;EACL,MAAM;EACN,QAAQ;EACR;EACA,SAAS,CAAC;GAAE,SAAS;GAA4C;EAAO,CAAC;CAC3E,EACF;AACF;AAMA,SAAgB,MAAuC,QAAW,MAA0B;CAC1F,MAAM,SAAS,OAAO,UAAU,IAAI;CACpC,IAAI,OAAO,SACT,OAAO;EACL,OAAO;EACP,MAAM,OAAO;CACf;CAmBF,OAAO;EAAE,OAAA,EARP,OAAO;GACL,MAAM;GACN,QAAQ;GACR,SAAS;GACT,SAAS,CAAC;IAAE,SAAS;IAA6C,iBAZ9C,OAAO,MAAM,OAAO,KAAK,EAAE,MAAM,MAAM,eAAe;KAC5E,OAAO,KAAK,KAAK,GAAG;KACpB,aAAa;KACb,QAAQ,KAAK,YAAY;KACzB,kBAAkB;MAAE,QAAQ;MAAS;KAAQ;IAC/C,EAOoF;GAAE,CAAC;EACrF,EAGW;EAAG,MAAM;CAAK;AAC7B;AAEA,eAAsB,qBAAqB,QAAgB,OAAe;CAQxE,KAAI,OADgB,MANG,MAAM,6DAA6D;EACxF,QAAQ;EACR,SAAS,EAAE,gBAAgB,oCAAoC;EAC/D,MAAM,IAAI,gBAAgB;GAAE;GAAQ,UAAU;EAAM,CAAC;CACvD,CAAC,EAAA,CAE4B,KAAK,EAAA,CACzB,SAAS,OAAO,EAAE,OAAO,KAAK;CACvC,OAAO,EAAE,OAAO,gBAAgB,+BAA+B,EAAE;AACnE"}
|