@prosopo/user-access-policy 3.5.19 → 3.5.28

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.
Files changed (93) hide show
  1. package/CHANGELOG.md +84 -0
  2. package/dist/.export.js +21 -0
  3. package/dist/api/.export.js +11 -0
  4. package/dist/api/delete/.export.js +1 -0
  5. package/dist/api/{deleteAllRulesEndpoint.js → delete/deleteAllRules.js} +10 -9
  6. package/dist/api/delete/deleteRuleGroups.js +52 -0
  7. package/dist/api/delete/deleteRules.js +43 -0
  8. package/dist/api/read/.export.js +1 -0
  9. package/dist/api/read/fetchRules.js +43 -0
  10. package/dist/api/read/findRuleIds.js +50 -0
  11. package/dist/api/read/getMissingIds.js +41 -0
  12. package/dist/api/ruleApiRoutes.js +131 -0
  13. package/dist/api/rulesApiClient.js +93 -0
  14. package/dist/api/write/.export.js +1 -0
  15. package/dist/api/write/insertRules.js +102 -0
  16. package/dist/api/write/rehashRules.js +57 -0
  17. package/dist/cjs/.export.cjs +21 -0
  18. package/dist/cjs/api/.export.cjs +11 -0
  19. package/dist/cjs/api/delete/.export.cjs +1 -0
  20. package/dist/cjs/api/{deleteAllRulesEndpoint.cjs → delete/deleteAllRules.cjs} +9 -8
  21. package/dist/cjs/api/delete/deleteRuleGroups.cjs +52 -0
  22. package/dist/cjs/api/delete/deleteRules.cjs +43 -0
  23. package/dist/cjs/api/read/.export.cjs +1 -0
  24. package/dist/cjs/api/read/fetchRules.cjs +43 -0
  25. package/dist/cjs/api/read/findRuleIds.cjs +50 -0
  26. package/dist/cjs/api/read/getMissingIds.cjs +41 -0
  27. package/dist/cjs/api/ruleApiRoutes.cjs +131 -0
  28. package/dist/cjs/api/rulesApiClient.cjs +93 -0
  29. package/dist/cjs/api/write/.export.cjs +1 -0
  30. package/dist/cjs/api/write/insertRules.cjs +102 -0
  31. package/dist/cjs/api/write/rehashRules.cjs +57 -0
  32. package/dist/cjs/mongoose/.export.cjs +4 -0
  33. package/dist/cjs/mongoose/mongooseRuleSchema.cjs +36 -0
  34. package/dist/cjs/redis/.export.cjs +6 -0
  35. package/dist/cjs/redis/reader/redisAggregate.cjs +60 -0
  36. package/dist/cjs/redis/reader/redisRulesQuery.cjs +99 -0
  37. package/dist/cjs/redis/reader/redisRulesReader.cjs +230 -0
  38. package/dist/cjs/redis/redisClient.cjs +67 -0
  39. package/dist/cjs/redis/redisRuleIndex.cjs +50 -0
  40. package/dist/cjs/redis/redisRulesStorage.cjs +22 -9
  41. package/dist/cjs/redis/redisRulesWriter.cjs +91 -64
  42. package/dist/cjs/rule.cjs +8 -0
  43. package/dist/cjs/ruleInput/.export.cjs +9 -0
  44. package/dist/cjs/ruleInput/policyInput.cjs +25 -0
  45. package/dist/cjs/ruleInput/ruleInput.cjs +50 -0
  46. package/dist/cjs/ruleInput/userScopeInput.cjs +55 -0
  47. package/dist/cjs/ruleRecord.cjs +23 -0
  48. package/dist/cjs/rulesStorage.cjs +8 -0
  49. package/dist/cjs/transformRule.cjs +77 -0
  50. package/dist/mongoose/.export.js +4 -0
  51. package/dist/mongoose/mongooseRuleSchema.js +36 -0
  52. package/dist/redis/.export.js +6 -0
  53. package/dist/redis/reader/redisAggregate.js +60 -0
  54. package/dist/redis/reader/redisRulesQuery.js +99 -0
  55. package/dist/redis/reader/redisRulesReader.js +213 -0
  56. package/dist/redis/redisClient.js +67 -0
  57. package/dist/redis/redisRuleIndex.js +50 -0
  58. package/dist/redis/redisRulesStorage.js +23 -10
  59. package/dist/redis/redisRulesWriter.js +91 -64
  60. package/dist/rule.js +8 -0
  61. package/dist/ruleInput/.export.js +9 -0
  62. package/dist/ruleInput/policyInput.js +25 -0
  63. package/dist/ruleInput/ruleInput.js +50 -0
  64. package/dist/ruleInput/userScopeInput.js +55 -0
  65. package/dist/ruleRecord.js +23 -0
  66. package/dist/rulesStorage.js +8 -0
  67. package/dist/transformRule.js +77 -0
  68. package/entries.ts +20 -0
  69. package/package.json +34 -18
  70. package/vite.cjs.config.ts +4 -1
  71. package/vite.esm.config.ts +6 -1
  72. package/dist/accessPolicy.js +0 -80
  73. package/dist/accessPolicyResolver.js +0 -31
  74. package/dist/accessRules.js +0 -11
  75. package/dist/api/accessRuleApiRoutes.js +0 -79
  76. package/dist/api/accessRulesApiClient.js +0 -38
  77. package/dist/api/deleteRulesEndpoint.js +0 -34
  78. package/dist/api/insertRulesEndpoint.js +0 -62
  79. package/dist/cjs/accessPolicy.cjs +0 -80
  80. package/dist/cjs/accessPolicyResolver.cjs +0 -31
  81. package/dist/cjs/accessRules.cjs +0 -11
  82. package/dist/cjs/api/accessRuleApiRoutes.cjs +0 -79
  83. package/dist/cjs/api/accessRulesApiClient.cjs +0 -38
  84. package/dist/cjs/api/deleteRulesEndpoint.cjs +0 -34
  85. package/dist/cjs/api/insertRulesEndpoint.cjs +0 -62
  86. package/dist/cjs/index.cjs +0 -31
  87. package/dist/cjs/redis/redisRulesIndex.cjs +0 -138
  88. package/dist/cjs/redis/redisRulesReader.cjs +0 -142
  89. package/dist/cjs/util.cjs +0 -5
  90. package/dist/index.js +0 -32
  91. package/dist/redis/redisRulesIndex.js +0 -138
  92. package/dist/redis/redisRulesReader.js +0 -125
  93. package/dist/util.js +0 -5
@@ -0,0 +1 @@
1
+ "use strict";
@@ -0,0 +1,102 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const apiRoute = require("@prosopo/api-route");
4
+ const common = require("@prosopo/common");
5
+ const zod = require("zod");
6
+ const policyInput = require("../../ruleInput/policyInput.cjs");
7
+ const userScopeInput = require("../../ruleInput/userScopeInput.cjs");
8
+ class InsertRulesEndpoint {
9
+ constructor(accessRulesWriter, logger) {
10
+ this.accessRulesWriter = accessRulesWriter;
11
+ this.logger = logger;
12
+ }
13
+ getRequestArgsSchema() {
14
+ return zod.z.array(
15
+ zod.z.object({
16
+ accessPolicy: policyInput.accessPolicyInput,
17
+ policyScopes: zod.z.array(policyInput.policyScopeInput).optional(),
18
+ groupId: zod.z.string().optional(),
19
+ userScopes: zod.z.array(userScopeInput.userScopeInput),
20
+ expiresUnixTimestamp: zod.z.number().optional()
21
+ })
22
+ );
23
+ }
24
+ async processRequest(args) {
25
+ const timeoutPromise = new Promise((resolve) => {
26
+ setTimeout(() => {
27
+ resolve({
28
+ status: apiRoute.ApiEndpointResponseStatus.PROCESSING
29
+ });
30
+ }, 5e3);
31
+ });
32
+ const userScopesCount = args.reduce(
33
+ (userScopesCount2, group) => userScopesCount2 + group.userScopes.length,
34
+ 0
35
+ );
36
+ const createRulesPromise = this.createRuleGroups(args).then((insertedIds) => {
37
+ this.logger.info(() => ({
38
+ msg: "Endpoint inserted access rules",
39
+ data: {
40
+ userScopesCount,
41
+ insertedCount: insertedIds.length,
42
+ uniqueIdsCount: new Set(insertedIds).size
43
+ }
44
+ }));
45
+ this.logger.debug(() => ({
46
+ msg: "Inserted access rules details",
47
+ data: {
48
+ insertedIds,
49
+ input: args
50
+ }
51
+ }));
52
+ return {
53
+ status: apiRoute.ApiEndpointResponseStatus.SUCCESS
54
+ };
55
+ }).catch((error) => {
56
+ if (common.LogLevel.enum.debug === this.logger.getLogLevel()) {
57
+ this.logger.error(() => ({
58
+ err: error,
59
+ data: { args },
60
+ msg: "Failed to insert access rules"
61
+ }));
62
+ }
63
+ return {
64
+ status: apiRoute.ApiEndpointResponseStatus.FAIL
65
+ };
66
+ });
67
+ return Promise.race([timeoutPromise, createRulesPromise]);
68
+ }
69
+ async createRuleGroups(groups) {
70
+ const ruleIdPromises = groups.map((group) => this.createRulesGroup(group));
71
+ const ruleIdSets = await Promise.all(ruleIdPromises);
72
+ return ruleIdSets.flat();
73
+ }
74
+ async createRulesGroup(group) {
75
+ const ruleEntries = [];
76
+ const policyScopes = group.policyScopes || [];
77
+ for (const userScope of group.userScopes) {
78
+ const ruleBase = {
79
+ ...group.accessPolicy,
80
+ ...userScope,
81
+ ...group.groupId ? { groupId: group.groupId } : {}
82
+ };
83
+ if (policyScopes.length > 0) {
84
+ for (const policyScope of policyScopes) {
85
+ ruleEntries.push({
86
+ rule: {
87
+ ...ruleBase,
88
+ ...policyScope
89
+ }
90
+ });
91
+ }
92
+ } else {
93
+ ruleEntries.push({
94
+ rule: ruleBase,
95
+ expiresUnixTimestamp: group.expiresUnixTimestamp
96
+ });
97
+ }
98
+ }
99
+ return this.accessRulesWriter.insertRules(ruleEntries);
100
+ }
101
+ }
102
+ exports.InsertRulesEndpoint = InsertRulesEndpoint;
@@ -0,0 +1,57 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const apiRoute = require("@prosopo/api-route");
4
+ class RehashRulesEndpoint {
5
+ constructor(accessRulesStorage, logger) {
6
+ this.accessRulesStorage = accessRulesStorage;
7
+ this.logger = logger;
8
+ }
9
+ getRequestArgsSchema() {
10
+ }
11
+ async processRequest() {
12
+ await this.accessRulesStorage.fetchAllRuleIds(async (ruleIds) => {
13
+ this.logger.info(() => ({
14
+ msg: "Fetched rule ids batch",
15
+ data: {
16
+ count: ruleIds.length,
17
+ ruleIds
18
+ }
19
+ }));
20
+ const ruleEntries = await this.accessRulesStorage.fetchRules(ruleIds);
21
+ this.logger.info(() => ({
22
+ msg: "Fetched rules",
23
+ data: {
24
+ count: ruleEntries.length
25
+ }
26
+ }));
27
+ if (ruleEntries.length !== ruleIds.length) {
28
+ this.logger.warn(() => ({
29
+ msg: "Fetched rules count is not equal to the requested count",
30
+ data: {
31
+ fetchedCount: ruleEntries.length,
32
+ requestedCount: ruleIds.length
33
+ }
34
+ }));
35
+ }
36
+ await this.accessRulesStorage.deleteRules(ruleIds);
37
+ this.logger.info(() => ({
38
+ msg: "Deleted rules",
39
+ data: {
40
+ count: ruleIds.length
41
+ }
42
+ }));
43
+ await this.accessRulesStorage.insertRules(ruleEntries);
44
+ this.logger.info(() => ({
45
+ msg: "Inserted rules",
46
+ data: {
47
+ count: ruleEntries.length
48
+ }
49
+ }));
50
+ });
51
+ return {
52
+ status: apiRoute.ApiEndpointResponseStatus.SUCCESS,
53
+ data: {}
54
+ };
55
+ }
56
+ }
57
+ exports.RehashRulesEndpoint = RehashRulesEndpoint;
@@ -0,0 +1,4 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const mongooseRuleSchema = require("./mongooseRuleSchema.cjs");
4
+ exports.accessRuleMongooseSchema = mongooseRuleSchema.accessRuleMongooseSchema;
@@ -0,0 +1,36 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const userAttributesSchema = {
4
+ userId: { type: String, required: false },
5
+ ja4Hash: { type: String, required: false },
6
+ userAgent: { type: String, required: false },
7
+ headersHash: { type: String, required: false }
8
+ };
9
+ const userIpSchema = {
10
+ ip: { type: String, required: false },
11
+ ipMask: { type: String, required: false }
12
+ };
13
+ const userScopeSchema = {
14
+ ...userAttributesSchema,
15
+ ...userIpSchema
16
+ };
17
+ const policyScopeSchema = {
18
+ clientId: { type: String, required: false }
19
+ };
20
+ const accessPolicySchema = {
21
+ type: { type: String, required: true },
22
+ captchaType: { type: String, required: false },
23
+ description: { type: String, required: false },
24
+ solvedImagesCount: { type: Number, required: false },
25
+ imageThreshold: { type: Number, required: false },
26
+ powDifficulty: { type: Number, required: false },
27
+ unsolvedImagesCount: { type: Number, required: false },
28
+ frictionlessScore: { type: Number, required: false }
29
+ };
30
+ const accessRuleMongooseSchema = {
31
+ ...accessPolicySchema,
32
+ ...policyScopeSchema,
33
+ ...userScopeSchema,
34
+ ruleGroupId: { type: String, required: false }
35
+ };
36
+ exports.accessRuleMongooseSchema = accessRuleMongooseSchema;
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const redisRulesStorage = require("./redisRulesStorage.cjs");
4
+ const redisRuleIndex = require("./redisRuleIndex.cjs");
5
+ exports.createRedisAccessRulesStorage = redisRulesStorage.createRedisAccessRulesStorage;
6
+ exports.accessRulesRedisIndex = redisRuleIndex.accessRulesRedisIndex;
@@ -0,0 +1,60 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const zod = require("zod");
4
+ const redisRulesQuery = require("./redisRulesQuery.cjs");
5
+ const redisClient = require("../redisClient.cjs");
6
+ const redisRuleIndex = require("../redisRuleIndex.cjs");
7
+ const aggregateRedisKeys = async (client, query, logger, batchHandler) => {
8
+ const keyField = "__key";
9
+ const recordSchema = zod.z.object({
10
+ // it's a reserved name for the record key
11
+ [keyField]: zod.z.string()
12
+ });
13
+ const foundKeys = [];
14
+ const addRecordKeys = async (records) => {
15
+ const parsedRecords = redisClient.parseRedisRecords(records, recordSchema, logger);
16
+ const recordKeys = parsedRecords.map((record) => record[keyField]);
17
+ if (batchHandler) {
18
+ await batchHandler(recordKeys);
19
+ } else {
20
+ foundKeys.push(...recordKeys);
21
+ logger.debug(() => ({
22
+ msg: "Processed aggregation batch",
23
+ data: {
24
+ size: recordKeys.length
25
+ }
26
+ }));
27
+ }
28
+ };
29
+ await executeAggregation(
30
+ client,
31
+ query,
32
+ {
33
+ // #2 is a required option when the 'ismissing()' function is in the query body
34
+ DIALECT: redisRulesQuery.REDIS_QUERY_DIALECT,
35
+ COUNT: redisClient.REDIS_BATCH_SIZE,
36
+ LOAD: `@${keyField}`
37
+ },
38
+ addRecordKeys
39
+ );
40
+ return foundKeys;
41
+ };
42
+ const executeAggregation = async (client, query, aggregateOptions, handleBatch) => {
43
+ const initialReply = await client.ft.aggregateWithCursor(
44
+ redisRuleIndex.ACCESS_RULES_REDIS_INDEX_NAME,
45
+ query,
46
+ aggregateOptions
47
+ );
48
+ await handleBatch(initialReply.results);
49
+ let cursor = initialReply.cursor;
50
+ while (0 !== cursor) {
51
+ const batchReply = await client.ft.cursorRead(
52
+ redisRuleIndex.ACCESS_RULES_REDIS_INDEX_NAME,
53
+ cursor,
54
+ { COUNT: aggregateOptions.COUNT }
55
+ );
56
+ await handleBatch(batchReply.results);
57
+ cursor = batchReply.cursor;
58
+ }
59
+ };
60
+ exports.aggregateRedisKeys = aggregateRedisKeys;
@@ -0,0 +1,99 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const userScopeInput = require("../../ruleInput/userScopeInput.cjs");
4
+ const rulesStorage = require("../../rulesStorage.cjs");
5
+ const REDIS_QUERY_DIALECT = 2;
6
+ const userIpQueries = {
7
+ numericIp: (value, scope) => {
8
+ if (void 0 !== value) {
9
+ return `( @numericIp:[${value} ${value}] | ( @numericIpMaskMin:[-inf ${value}] @numericIpMaskMax:[${value} +inf] ) )`;
10
+ }
11
+ if (scope.numericIpMaskMin === void 0 && scope.numericIpMaskMax === void 0) {
12
+ return "ismissing(@numericIp) ismissing(@numericIpMaskMin) ismissing(@numericIpMaskMax)";
13
+ }
14
+ return "";
15
+ },
16
+ numericIpMaskMin: (value, scope) => {
17
+ if (scope.numericIp !== void 0) {
18
+ return "";
19
+ }
20
+ return value !== void 0 ? `@numericIpMaskMin:[-inf ${value}]` : "ismissing(@numericIpMaskMin)";
21
+ },
22
+ numericIpMaskMax: (value, scope) => {
23
+ if (scope.numericIp !== void 0) {
24
+ return "";
25
+ }
26
+ return value !== void 0 ? `@numericIpMaskMax:[${value} +inf]` : "ismissing(@numericIpMaskMax)";
27
+ }
28
+ };
29
+ const getUserScopeQuery = (userScope, FilterScopeMatchType, matchingFieldsOnly) => {
30
+ let scopeEntries = Object.entries(userScope);
31
+ let scopeJoinType = " ";
32
+ if (FilterScopeMatchType === rulesStorage.FilterScopeMatch.Greedy) {
33
+ scopeEntries = scopeEntries.filter(
34
+ ([_, value]) => value !== void 0
35
+ );
36
+ scopeJoinType = " | ";
37
+ }
38
+ if (matchingFieldsOnly) {
39
+ const scopeMap = new Map(scopeEntries);
40
+ if (scopeMap.has("numericIp") && scopeMap.get("numericIp") === void 0) {
41
+ scopeMap.set("numericIpMaskMin", void 0);
42
+ scopeMap.set("numericIpMaskMax", void 0);
43
+ }
44
+ for (const name of Object.keys(userScopeInput.userScopeSchema.shape)) {
45
+ if (!scopeMap.has(name)) {
46
+ scopeMap.set(name, void 0);
47
+ }
48
+ }
49
+ scopeEntries = [...scopeMap.entries()];
50
+ }
51
+ const scopeObj = Object.fromEntries(scopeEntries);
52
+ return scopeEntries.map(
53
+ ([scopeFieldName, scopeFieldValue]) => getUserScopeFieldQuery(
54
+ scopeFieldName,
55
+ scopeFieldValue,
56
+ FilterScopeMatchType,
57
+ scopeObj
58
+ )
59
+ ).filter(Boolean).join(scopeJoinType);
60
+ };
61
+ const getUserScopeFieldQuery = (fieldName, fieldValue, scopeMatch, fullScope) => {
62
+ if (fieldName in userIpQueries) {
63
+ const queryBuilder = userIpQueries[fieldName];
64
+ return queryBuilder(fieldValue, fullScope);
65
+ }
66
+ return void 0 === fieldValue ? `ismissing(@${fieldName})` : `@${fieldName}:{${fieldValue}}`;
67
+ };
68
+ const getPolicyScopeQuery = (policyScope, scopeMatch) => {
69
+ const clientId = policyScope?.clientId;
70
+ if ("string" === typeof clientId) {
71
+ return rulesStorage.FilterScopeMatch.Exact === scopeMatch ? `@clientId:{${clientId}}` : `( @clientId:{${clientId}} | ismissing(@clientId) )`;
72
+ }
73
+ return rulesStorage.FilterScopeMatch.Exact === scopeMatch ? "ismissing(@clientId)" : "";
74
+ };
75
+ const getRulesRedisQuery = (filter, matchingFieldsOnly) => {
76
+ const { policyScope, userScope } = filter;
77
+ const queryParts = [];
78
+ if (filter.groupId) {
79
+ queryParts.push(`@groupId:{${filter.groupId}}`);
80
+ }
81
+ const policyScopeQuery = getPolicyScopeQuery(
82
+ policyScope,
83
+ filter.policyScopeMatch
84
+ );
85
+ if (policyScopeQuery) {
86
+ queryParts.push(policyScopeQuery);
87
+ }
88
+ if (userScope && Object.keys(userScope).length > 0) {
89
+ const userScopeFilter = getUserScopeQuery(
90
+ userScope,
91
+ filter.userScopeMatch,
92
+ matchingFieldsOnly
93
+ );
94
+ queryParts.push(`( ${userScopeFilter} )`);
95
+ }
96
+ return queryParts.length > 0 ? queryParts.join(" ") : "*";
97
+ };
98
+ exports.REDIS_QUERY_DIALECT = REDIS_QUERY_DIALECT;
99
+ exports.getRulesRedisQuery = getRulesRedisQuery;
@@ -0,0 +1,230 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const util = require("node:util");
4
+ const common = require("@prosopo/common");
5
+ const redisRulesQuery = require("./redisRulesQuery.cjs");
6
+ const redisClient = require("../redisClient.cjs");
7
+ const redisRuleIndex = require("../redisRuleIndex.cjs");
8
+ const ruleInput = require("../../ruleInput/ruleInput.cjs");
9
+ const redisAggregate = require("./redisAggregate.cjs");
10
+ function _interopNamespaceDefault(e) {
11
+ const n = Object.create(null, { [Symbol.toStringTag]: { value: "Module" } });
12
+ if (e) {
13
+ for (const k in e) {
14
+ if (k !== "default") {
15
+ const d = Object.getOwnPropertyDescriptor(e, k);
16
+ Object.defineProperty(n, k, d.get ? d : {
17
+ enumerable: true,
18
+ get: () => e[k]
19
+ });
20
+ }
21
+ }
22
+ }
23
+ n.default = e;
24
+ return Object.freeze(n);
25
+ }
26
+ const util__namespace = /* @__PURE__ */ _interopNamespaceDefault(util);
27
+ class RedisRulesReader {
28
+ constructor(client, logger) {
29
+ this.client = client;
30
+ this.logger = logger;
31
+ }
32
+ async getMissingRuleIds(ruleIds) {
33
+ const ruleKeys = this.getRuleKeys(ruleIds);
34
+ const keyBatches = common.chunkIntoBatches(ruleKeys, redisClient.REDIS_BATCH_SIZE);
35
+ const missingKeyBatches = await common.executeBatchesSequentially(
36
+ keyBatches,
37
+ async (keysBatch) => redisClient.getMissingRedisKeys(this.client, keysBatch)
38
+ );
39
+ return missingKeyBatches.flat().map((ruleKey) => ruleKey.slice(redisRuleIndex.ACCESS_RULE_REDIS_KEY_PREFIX.length));
40
+ }
41
+ async fetchRules(ruleIds) {
42
+ const ruleKeys = this.getRuleKeys(ruleIds);
43
+ const keyBatches = common.chunkIntoBatches(ruleKeys, redisClient.REDIS_BATCH_SIZE);
44
+ const entryBatches = await common.executeBatchesSequentially(
45
+ keyBatches,
46
+ (keysBatch) => this.fetchRuleEntries(keysBatch)
47
+ );
48
+ return entryBatches.flat();
49
+ }
50
+ async findRules(filter, matchingFieldsOnly = false, skipEmptyUserScopes = true) {
51
+ const query = redisRulesQuery.getRulesRedisQuery(filter, matchingFieldsOnly);
52
+ if (skipEmptyUserScopes && query === "ismissing(@clientId)") {
53
+ return [];
54
+ }
55
+ let searchReply;
56
+ try {
57
+ searchReply = await this.client.ft.search(
58
+ redisRuleIndex.ACCESS_RULES_REDIS_INDEX_NAME,
59
+ query,
60
+ {
61
+ DIALECT: redisRulesQuery.REDIS_QUERY_DIALECT,
62
+ // FT.search doesn't support "unlimited" selects
63
+ LIMIT: {
64
+ from: 0,
65
+ size: redisClient.REDIS_BATCH_SIZE
66
+ }
67
+ }
68
+ );
69
+ if (searchReply.total > 0) {
70
+ this.logger.debug(() => ({
71
+ msg: "Executed search query",
72
+ data: {
73
+ inspect: util__namespace.inspect(
74
+ {
75
+ filter,
76
+ searchReply,
77
+ query
78
+ },
79
+ { depth: null }
80
+ )
81
+ }
82
+ }));
83
+ }
84
+ } catch (e) {
85
+ this.logger.error(() => ({
86
+ err: e,
87
+ data: {
88
+ inspect: util__namespace.inspect(
89
+ {
90
+ query,
91
+ filter
92
+ },
93
+ {
94
+ depth: null
95
+ }
96
+ )
97
+ },
98
+ msg: "failed to execute search query"
99
+ }));
100
+ return [];
101
+ }
102
+ const records = searchReply.documents.map(({ value }) => value);
103
+ return redisClient.parseRedisRecords(records, ruleInput.accessRuleInput, this.logger);
104
+ }
105
+ async findRuleIds(filter, matchingFieldsOnly = false) {
106
+ const query = redisRulesQuery.getRulesRedisQuery(filter, matchingFieldsOnly);
107
+ let ruleIds = [];
108
+ try {
109
+ const ruleKeys = await redisAggregate.aggregateRedisKeys(
110
+ this.client,
111
+ query,
112
+ this.logger
113
+ );
114
+ ruleIds = ruleKeys.map(
115
+ (ruleKey) => ruleKey.slice(redisRuleIndex.ACCESS_RULE_REDIS_KEY_PREFIX.length)
116
+ );
117
+ } catch (e) {
118
+ this.logger.error(() => ({
119
+ err: e,
120
+ data: {
121
+ inspect: util__namespace.inspect(
122
+ {
123
+ query,
124
+ filter
125
+ },
126
+ {
127
+ depth: null
128
+ }
129
+ )
130
+ },
131
+ msg: "Failed to execute search query for rule IDs"
132
+ }));
133
+ return [];
134
+ }
135
+ this.logger.debug(() => ({
136
+ msg: "Executed search query for rule IDs",
137
+ data: {
138
+ query,
139
+ foundCount: ruleIds.length,
140
+ foundIds: ruleIds
141
+ }
142
+ }));
143
+ return ruleIds;
144
+ }
145
+ async fetchAllRuleIds(batchHandler) {
146
+ const keysBatchHandler = async (keys) => {
147
+ const ids = keys.map(
148
+ (ruleKey) => ruleKey.slice(redisRuleIndex.ACCESS_RULE_REDIS_KEY_PREFIX.length)
149
+ );
150
+ await batchHandler(ids);
151
+ };
152
+ await redisAggregate.aggregateRedisKeys(this.client, "*", this.logger, keysBatchHandler);
153
+ }
154
+ async fetchRuleEntries(keys) {
155
+ const { records, expirations } = await redisClient.fetchRedisHashRecords(
156
+ this.client,
157
+ keys,
158
+ this.logger
159
+ );
160
+ const entries = [];
161
+ for (const [index, ruleData] of records.entries()) {
162
+ const isRulePresent = Object.keys(ruleData).length > 0;
163
+ if (isRulePresent) {
164
+ const rule = redisClient.parseRedisRecords(
165
+ [ruleData],
166
+ ruleInput.accessRuleInput,
167
+ this.logger
168
+ )[0];
169
+ if (rule) {
170
+ entries.push({
171
+ rule,
172
+ expiresUnixTimestamp: expirations[index]
173
+ });
174
+ }
175
+ }
176
+ }
177
+ return entries;
178
+ }
179
+ getRuleKeys(ruleIds) {
180
+ return ruleIds.map((id) => `${redisRuleIndex.ACCESS_RULE_REDIS_KEY_PREFIX}${id}`);
181
+ }
182
+ }
183
+ class DummyRedisRulesReader {
184
+ constructor(logger) {
185
+ this.logger = logger;
186
+ }
187
+ async getMissingRuleIds(ruleIds) {
188
+ this.logger.info(() => ({
189
+ msg: "Dummy getMissingRuleIds() has no effect (redis is not ready)",
190
+ data: {
191
+ ruleIds
192
+ }
193
+ }));
194
+ return [];
195
+ }
196
+ async fetchRules(ruleIds) {
197
+ this.logger.info(() => ({
198
+ msg: "Dummy fetchRule() has no effect (redis is not ready)",
199
+ data: {
200
+ ruleIds
201
+ }
202
+ }));
203
+ return [];
204
+ }
205
+ async findRules(filter, matchingFieldsOnly = false, skipEmptyUserScopes = true) {
206
+ this.logger.info(() => ({
207
+ msg: "Dummy findRules() has no effect (redis is not ready)",
208
+ data: {
209
+ filter
210
+ }
211
+ }));
212
+ return [];
213
+ }
214
+ async findRuleIds(filter, matchingFieldsOnly = false) {
215
+ this.logger.info(() => ({
216
+ msg: "Dummy findRuleIds() has no effect (redis is not ready)",
217
+ data: {
218
+ filter
219
+ }
220
+ }));
221
+ return [];
222
+ }
223
+ async fetchAllRuleIds(batchHandler) {
224
+ this.logger.info(() => ({
225
+ msg: "Dummy fetchAllRuleIds() has no effect (redis is not ready)"
226
+ }));
227
+ }
228
+ }
229
+ exports.DummyRedisRulesReader = DummyRedisRulesReader;
230
+ exports.RedisRulesReader = RedisRulesReader;
@@ -0,0 +1,67 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const zod = require("zod");
4
+ const REDIS_BATCH_SIZE = 1e3;
5
+ const getMissingRedisKeys = async (client, keys) => {
6
+ const queries = client.multi();
7
+ keys.map((key) => {
8
+ queries.exists(key);
9
+ });
10
+ const records = await queries.exec();
11
+ const missingKeys = [];
12
+ records.map((exists, recordIndex) => {
13
+ if ("0" === String(exists)) {
14
+ const key = keys[recordIndex];
15
+ if (key) {
16
+ missingKeys.push(key);
17
+ }
18
+ }
19
+ });
20
+ return missingKeys;
21
+ };
22
+ const fetchRedisHashRecords = async (client, keys, logger) => {
23
+ const rulesPipe = client.multi();
24
+ const expirationPipe = client.multi();
25
+ for (const key of keys) {
26
+ rulesPipe.hGetAll(key);
27
+ expirationPipe.expireTime(key);
28
+ }
29
+ const records = await rulesPipe.exec();
30
+ const expirationRecords = await expirationPipe.exec();
31
+ return {
32
+ records,
33
+ expirations: parseExpirationRecords(expirationRecords, logger)
34
+ };
35
+ };
36
+ const parseRedisRecords = (records, recordSchema, logger) => records.flatMap((record) => {
37
+ const parseResult = recordSchema.safeParse(record);
38
+ if (parseResult.success) {
39
+ return [parseResult.data];
40
+ }
41
+ logger.error(() => ({
42
+ msg: "Failed to parse Redis record",
43
+ data: { record, error: parseResult.error }
44
+ }));
45
+ return [];
46
+ });
47
+ const expirationRecordSchema = zod.z.coerce.number();
48
+ const UNSET_EXPIRATION_VALUE = -1;
49
+ const parseExpirationRecords = (records, logger) => records.flatMap((record) => {
50
+ const parseResult = expirationRecordSchema.safeParse(record);
51
+ if (parseResult.success) {
52
+ const expiration = UNSET_EXPIRATION_VALUE === parseResult.data ? void 0 : parseResult.data;
53
+ return [expiration];
54
+ }
55
+ logger.error(() => ({
56
+ msg: "Failed to parse Redis expiration record",
57
+ data: {
58
+ record,
59
+ error: parseResult.error
60
+ }
61
+ }));
62
+ return [void 0];
63
+ });
64
+ exports.REDIS_BATCH_SIZE = REDIS_BATCH_SIZE;
65
+ exports.fetchRedisHashRecords = fetchRedisHashRecords;
66
+ exports.getMissingRedisKeys = getMissingRedisKeys;
67
+ exports.parseRedisRecords = parseRedisRecords;