@arcis/node 1.1.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.md +156 -211
  2. package/dist/core/index.d.mts +4 -4
  3. package/dist/core/index.d.ts +4 -4
  4. package/dist/core/index.js +13 -2
  5. package/dist/core/index.js.map +1 -1
  6. package/dist/core/index.mjs +13 -2
  7. package/dist/core/index.mjs.map +1 -1
  8. package/dist/{index-CslcoZUN.d.mts → index-A-m-pPeW.d.mts} +1 -1
  9. package/dist/{index-CCcPuTBo.d.mts → index-CgK94hY_.d.mts} +96 -2
  10. package/dist/{index-iCOw8Fcg.d.ts → index-Co5kPRZz.d.ts} +1 -1
  11. package/dist/{index-BvcFpoR3.d.ts → index-D_bdJcF0.d.ts} +96 -2
  12. package/dist/index.d.mts +4 -4
  13. package/dist/index.d.ts +4 -4
  14. package/dist/index.js +553 -5
  15. package/dist/index.js.map +1 -1
  16. package/dist/index.mjs +540 -7
  17. package/dist/index.mjs.map +1 -1
  18. package/dist/logging/index.d.mts +1 -1
  19. package/dist/logging/index.d.ts +1 -1
  20. package/dist/logging/index.js +12 -1
  21. package/dist/logging/index.js.map +1 -1
  22. package/dist/logging/index.mjs +12 -1
  23. package/dist/logging/index.mjs.map +1 -1
  24. package/dist/middleware/index.d.mts +2 -2
  25. package/dist/middleware/index.d.ts +2 -2
  26. package/dist/middleware/index.js +146 -4
  27. package/dist/middleware/index.js.map +1 -1
  28. package/dist/middleware/index.mjs +143 -5
  29. package/dist/middleware/index.mjs.map +1 -1
  30. package/dist/{headers-DBQedhrb.d.mts → pii-CXcHMlnX.d.mts} +156 -2
  31. package/dist/{headers-BJq2OA0i.d.ts → pii-DhNpl7M3.d.ts} +156 -2
  32. package/dist/sanitizers/index.d.mts +2 -2
  33. package/dist/sanitizers/index.d.ts +2 -2
  34. package/dist/sanitizers/index.js +331 -3
  35. package/dist/sanitizers/index.js.map +1 -1
  36. package/dist/sanitizers/index.mjs +321 -4
  37. package/dist/sanitizers/index.mjs.map +1 -1
  38. package/dist/stores/index.d.mts +1 -1
  39. package/dist/stores/index.d.ts +1 -1
  40. package/dist/stores/index.js.map +1 -1
  41. package/dist/stores/index.mjs.map +1 -1
  42. package/dist/{types-BOdL3ZWo.d.mts → types-CsOFHoD9.d.mts} +6 -1
  43. package/dist/{types-BOdL3ZWo.d.ts → types-CsOFHoD9.d.ts} +6 -1
  44. package/dist/validation/index.d.mts +2 -2
  45. package/dist/validation/index.d.ts +2 -2
  46. package/dist/validation/index.js +105 -3
  47. package/dist/validation/index.js.map +1 -1
  48. package/dist/validation/index.mjs +105 -3
  49. package/dist/validation/index.mjs.map +1 -1
  50. package/package.json +114 -114
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { promises } from 'dns';
2
- import { createHash } from 'crypto';
2
+ import { randomBytes, createHash } from 'crypto';
3
3
 
4
4
  // src/core/constants.ts
5
5
  var INPUT = {
@@ -115,7 +115,11 @@ var SQL_PATTERNS = [
115
115
  /** Time-based blind: SLEEP() */
116
116
  /\bSLEEP\s*\(\s*\d+\s*\)/gi,
117
117
  /** Time-based blind: BENCHMARK() */
118
- /\bBENCHMARK\s*\(/gi
118
+ /\bBENCHMARK\s*\(/gi,
119
+ /** Time-based blind: PostgreSQL pg_sleep() */
120
+ /\bpg_sleep\s*\(/gi,
121
+ /** Time-based blind: MSSQL WAITFOR DELAY */
122
+ /\bWAITFOR\s+DELAY\b/gi
119
123
  ];
120
124
  var PATH_PATTERNS = [
121
125
  /** Unix path traversal */
@@ -133,6 +137,10 @@ var PATH_PATTERNS = [
133
137
  /\.%2e[\\/]/gi,
134
138
  /** Fully URL-encoded: %2e%2e%2f */
135
139
  /%2e%2e%2f/gi,
140
+ /** Double URL-encoded forward slash: %252f */
141
+ /%252f/gi,
142
+ /** Dotdotslash bypass: ....// or ....\\ */
143
+ /\.{2,}[/\\]{2,}/g,
136
144
  /** Null byte injection in paths */
137
145
  /\0/g
138
146
  ];
@@ -148,7 +156,9 @@ var COMMAND_PATTERNS = [
148
156
  */
149
157
  /[;&|`]/g,
150
158
  /** Command substitution: $( ... ) — matched as a pair to reduce false positives */
151
- /\$\(/g
159
+ /\$\(/g,
160
+ /** URL-encoded newline/carriage-return injection (%0a, %0d) */
161
+ /%0[ad]/gi
152
162
  ];
153
163
  var DANGEROUS_PROTO_KEYS = /* @__PURE__ */ new Set([
154
164
  "__proto__",
@@ -182,6 +192,7 @@ var NOSQL_DANGEROUS_KEYS = /* @__PURE__ */ new Set([
182
192
  "$expr",
183
193
  "$mod",
184
194
  "$text",
195
+ "$jsonSchema",
185
196
  // Array
186
197
  "$elemMatch",
187
198
  "$all",
@@ -782,7 +793,8 @@ function sanitizeObject(obj, options = {}) {
782
793
  if (typeof obj === "string") return sanitizeString(obj, options);
783
794
  if (typeof obj !== "object") return obj;
784
795
  if (Array.isArray(obj)) return obj.map((item) => sanitizeObject(item, options));
785
- return sanitizeObjectDepth(obj, options, 0);
796
+ const result = sanitizeObjectDepth(obj, options, 0);
797
+ return options.freeze ? Object.freeze(result) : result;
786
798
  }
787
799
  function sanitizeObjectDepth(obj, options, depth) {
788
800
  if (depth >= INPUT.MAX_RECURSION_DEPTH) return obj;
@@ -879,6 +891,179 @@ function detectPrototypePollution(obj, maxDepth = 10) {
879
891
  return false;
880
892
  }
881
893
 
894
+ // src/sanitizers/ssti.ts
895
+ var SSTI_DETECT_PATTERNS = [
896
+ /** Jinja2 / Twig / Nunjucks: {{ ... }} */
897
+ /\{\{.*?\}\}/g,
898
+ /** Freemarker / Thymeleaf / Spring EL: ${ ... } */
899
+ /\$\{.*?\}/g,
900
+ /** ERB / EJS: <%= ... %> or <% ... %> */
901
+ /<%[=\-]?.*?%>/gs,
902
+ /** Pug / Jade / Slim: #{ ... } */
903
+ /#\{.*?\}/g,
904
+ /** Python dunder sandbox escape */
905
+ /__(?:class|mro|subclasses|globals|builtins|import)__/gi,
906
+ /** Jinja2 config leak: {{config.X}} or {{config['X']}} */
907
+ /\{\{\s*config[.\[]/gi,
908
+ /** Jinja2 built-in objects */
909
+ /\{\{\s*(?:self|request|lipsum|cycler|joiner|namespace|range)\b/gi
910
+ ];
911
+ var SSTI_REMOVE_PATTERNS = [
912
+ /\{\{.*?\}\}/g,
913
+ /\$\{.*?\}/g,
914
+ /<%[=\-]?.*?%>/gs,
915
+ /#\{.*?\}/g,
916
+ /__(?:class|mro|subclasses|globals|builtins|import)__/gi
917
+ ];
918
+ function sanitizeSsti(input, collectThreats = false) {
919
+ if (typeof input !== "string") {
920
+ return collectThreats ? { value: String(input), wasSanitized: false, threats: [] } : String(input);
921
+ }
922
+ const threats = [];
923
+ let value = input;
924
+ let wasSanitized = false;
925
+ for (const pattern of SSTI_REMOVE_PATTERNS) {
926
+ pattern.lastIndex = 0;
927
+ if (pattern.test(value)) {
928
+ pattern.lastIndex = 0;
929
+ if (collectThreats) {
930
+ const matches = value.match(pattern);
931
+ if (matches) {
932
+ for (const match of matches) {
933
+ threats.push({
934
+ type: "ssti",
935
+ pattern: pattern.source,
936
+ original: match
937
+ });
938
+ }
939
+ }
940
+ }
941
+ value = value.replace(pattern, "");
942
+ wasSanitized = true;
943
+ }
944
+ }
945
+ if (collectThreats) {
946
+ return { value, wasSanitized, threats };
947
+ }
948
+ return value;
949
+ }
950
+ function detectSsti(input) {
951
+ if (typeof input !== "string") return false;
952
+ for (const pattern of SSTI_DETECT_PATTERNS) {
953
+ pattern.lastIndex = 0;
954
+ if (pattern.test(input)) {
955
+ return true;
956
+ }
957
+ }
958
+ return false;
959
+ }
960
+
961
+ // src/sanitizers/xxe.ts
962
+ var XXE_DETECT_PATTERNS = [
963
+ /** DOCTYPE declaration */
964
+ /<!DOCTYPE\b/gi,
965
+ /** ENTITY declaration */
966
+ /<!ENTITY\b/gi,
967
+ /** SYSTEM keyword with URI */
968
+ /\bSYSTEM\s+["']/gi,
969
+ /** PUBLIC keyword with URI */
970
+ /\bPUBLIC\s+["']/gi,
971
+ /** Parameter entity reference (%entity;) */
972
+ /%\s*\w+\s*;/g,
973
+ /** CDATA section (often used to smuggle payloads) */
974
+ /<!\[CDATA\[/gi
975
+ ];
976
+ var XXE_REMOVE_PATTERNS = [
977
+ /** Full DOCTYPE block with optional internal subset: <!DOCTYPE ... [...]> */
978
+ /<!DOCTYPE\s[^[>]*(?:\[[^\]]*\]\s*)?>|<!DOCTYPE\s[^>]*>/gi,
979
+ /** Full ENTITY declaration: <!ENTITY ... > */
980
+ /<!ENTITY[^>]*>/gi,
981
+ /** CDATA sections: <![CDATA[ ... ]]> */
982
+ /<!\[CDATA\[[\s\S]*?\]\]>/gi
983
+ ];
984
+ function sanitizeXxe(input, collectThreats = false) {
985
+ if (typeof input !== "string") {
986
+ return collectThreats ? { value: String(input), wasSanitized: false, threats: [] } : String(input);
987
+ }
988
+ const threats = [];
989
+ let value = input;
990
+ let wasSanitized = false;
991
+ for (const pattern of XXE_REMOVE_PATTERNS) {
992
+ pattern.lastIndex = 0;
993
+ if (pattern.test(value)) {
994
+ pattern.lastIndex = 0;
995
+ if (collectThreats) {
996
+ const matches = value.match(pattern);
997
+ if (matches) {
998
+ for (const match of matches) {
999
+ threats.push({
1000
+ type: "xxe",
1001
+ pattern: pattern.source,
1002
+ original: match
1003
+ });
1004
+ }
1005
+ }
1006
+ }
1007
+ value = value.replace(pattern, "");
1008
+ wasSanitized = true;
1009
+ }
1010
+ }
1011
+ if (collectThreats) {
1012
+ return { value, wasSanitized, threats };
1013
+ }
1014
+ return value;
1015
+ }
1016
+ function detectXxe(input) {
1017
+ if (typeof input !== "string") return false;
1018
+ for (const pattern of XXE_DETECT_PATTERNS) {
1019
+ pattern.lastIndex = 0;
1020
+ if (pattern.test(input)) {
1021
+ return true;
1022
+ }
1023
+ }
1024
+ return false;
1025
+ }
1026
+
1027
+ // src/sanitizers/jsonp.ts
1028
+ var SAFE_CALLBACK_PATTERN = /^[a-zA-Z_$][a-zA-Z0-9_$.[\]]*$/;
1029
+ var DANGEROUS_CALLBACK_PATTERNS = [
1030
+ /\.\./,
1031
+ // prototype chain traversal
1032
+ /\[\s*\]/
1033
+ // empty bracket access
1034
+ ];
1035
+ function sanitizeJsonpCallback(callback, maxLength = 128) {
1036
+ if (typeof callback !== "string" || callback.length === 0) {
1037
+ return null;
1038
+ }
1039
+ if (callback.length > maxLength) {
1040
+ return null;
1041
+ }
1042
+ if (!SAFE_CALLBACK_PATTERN.test(callback)) {
1043
+ return null;
1044
+ }
1045
+ for (const pattern of DANGEROUS_CALLBACK_PATTERNS) {
1046
+ if (pattern.test(callback)) {
1047
+ return null;
1048
+ }
1049
+ }
1050
+ return callback;
1051
+ }
1052
+ function detectJsonpInjection(callback) {
1053
+ if (typeof callback !== "string" || callback.length === 0) {
1054
+ return false;
1055
+ }
1056
+ if (!SAFE_CALLBACK_PATTERN.test(callback)) {
1057
+ return true;
1058
+ }
1059
+ for (const pattern of DANGEROUS_CALLBACK_PATTERNS) {
1060
+ if (pattern.test(callback)) {
1061
+ return true;
1062
+ }
1063
+ }
1064
+ return false;
1065
+ }
1066
+
882
1067
  // src/sanitizers/headers.ts
883
1068
  var HEADER_INJECTION_PATTERN = /\r\n|\r|\n|\0/g;
884
1069
  function sanitizeHeaderValue(input, collectThreats = false) {
@@ -928,6 +1113,138 @@ function detectHeaderInjection(input) {
928
1113
  return HEADER_INJECTION_PATTERN.test(input);
929
1114
  }
930
1115
 
1116
+ // src/sanitizers/pii.ts
1117
+ var EMAIL_RE = /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z]{2,})+/g;
1118
+ var PHONE_RE = /(?:\+?1[-.\s]?)?\(?[2-9]\d{2}\)?[-.\s]?\d{3}[-.\s]?\d{4}/g;
1119
+ var CREDIT_CARD_RE = /\b(?:\d[ -]*?){13,19}\b/g;
1120
+ var SSN_RE = /\b\d{3}[-\s]\d{2}[-\s]\d{4}\b/g;
1121
+ var IPV4_RE = /\b(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\b/g;
1122
+ var IPV6_RE = /\b(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}\b|\b(?:[0-9a-fA-F]{1,4}:){1,7}:|::(?:[0-9a-fA-F]{1,4}:){0,5}[0-9a-fA-F]{1,4}\b/g;
1123
+ var PATTERN_MAP = {
1124
+ email: [EMAIL_RE],
1125
+ phone: [PHONE_RE],
1126
+ credit_card: [CREDIT_CARD_RE],
1127
+ ssn: [SSN_RE],
1128
+ ip_address: [IPV4_RE, IPV6_RE]
1129
+ };
1130
+ var ALL_TYPES = ["email", "phone", "credit_card", "ssn", "ip_address"];
1131
+ var TYPE_LABELS = {
1132
+ email: "[EMAIL]",
1133
+ phone: "[PHONE]",
1134
+ credit_card: "[CREDIT_CARD]",
1135
+ ssn: "[SSN]",
1136
+ ip_address: "[IP_ADDRESS]"
1137
+ };
1138
+ function luhnCheck(value) {
1139
+ const digits = value.replace(/[\s-]/g, "");
1140
+ if (!/^\d{13,19}$/.test(digits)) return false;
1141
+ let sum = 0;
1142
+ let alternate = false;
1143
+ for (let i = digits.length - 1; i >= 0; i--) {
1144
+ let n = parseInt(digits[i], 10);
1145
+ if (alternate) {
1146
+ n *= 2;
1147
+ if (n > 9) n -= 9;
1148
+ }
1149
+ sum += n;
1150
+ alternate = !alternate;
1151
+ }
1152
+ return sum % 10 === 0;
1153
+ }
1154
+ function scanPii(input, options = {}) {
1155
+ if (!input || typeof input !== "string") return [];
1156
+ const types = options.types ?? ALL_TYPES;
1157
+ const matches = [];
1158
+ for (const type of types) {
1159
+ const patterns = PATTERN_MAP[type];
1160
+ if (!patterns) continue;
1161
+ for (const pattern of patterns) {
1162
+ const re = new RegExp(pattern.source, pattern.flags);
1163
+ let match;
1164
+ while ((match = re.exec(input)) !== null) {
1165
+ const value = match[0];
1166
+ if (type === "credit_card" && !luhnCheck(value)) continue;
1167
+ if (type === "ssn") {
1168
+ const area = parseInt(value.substring(0, 3), 10);
1169
+ if (area === 0 || area === 666 || area >= 900) continue;
1170
+ }
1171
+ matches.push({
1172
+ type,
1173
+ value,
1174
+ start: match.index,
1175
+ end: match.index + value.length
1176
+ });
1177
+ }
1178
+ }
1179
+ }
1180
+ matches.sort((a, b) => a.start - b.start);
1181
+ return matches;
1182
+ }
1183
+ function detectPii(input, options = {}) {
1184
+ return scanPii(input, options).length > 0;
1185
+ }
1186
+ function redactPii(input, options = {}) {
1187
+ if (!input || typeof input !== "string") return input;
1188
+ const matches = scanPii(input, options);
1189
+ if (matches.length === 0) return input;
1190
+ const replacement = options.replacement ?? "[REDACTED]";
1191
+ let result = input;
1192
+ for (let i = matches.length - 1; i >= 0; i--) {
1193
+ const m = matches[i];
1194
+ const label = options.typeLabels ? TYPE_LABELS[m.type] : replacement;
1195
+ result = result.substring(0, m.start) + label + result.substring(m.end);
1196
+ }
1197
+ return result;
1198
+ }
1199
+ function scanObjectPii(obj, options = {}, path = "") {
1200
+ const results = [];
1201
+ if (!obj || typeof obj !== "object") return results;
1202
+ for (const [key, value] of Object.entries(obj)) {
1203
+ const fieldPath = path ? `${path}.${key}` : key;
1204
+ if (typeof value === "string") {
1205
+ const matches = scanPii(value, options);
1206
+ for (const m of matches) {
1207
+ results.push({ ...m, field: fieldPath });
1208
+ }
1209
+ } else if (value && typeof value === "object" && !Array.isArray(value)) {
1210
+ results.push(...scanObjectPii(value, options, fieldPath));
1211
+ } else if (Array.isArray(value)) {
1212
+ for (let i = 0; i < value.length; i++) {
1213
+ const item = value[i];
1214
+ if (typeof item === "string") {
1215
+ const matches = scanPii(item, options);
1216
+ for (const m of matches) {
1217
+ results.push({ ...m, field: `${fieldPath}[${i}]` });
1218
+ }
1219
+ } else if (item && typeof item === "object") {
1220
+ results.push(...scanObjectPii(item, options, `${fieldPath}[${i}]`));
1221
+ }
1222
+ }
1223
+ }
1224
+ }
1225
+ return results;
1226
+ }
1227
+ function redactObjectPii(obj, options = {}) {
1228
+ if (!obj || typeof obj !== "object") return obj;
1229
+ const result = {};
1230
+ for (const [key, value] of Object.entries(obj)) {
1231
+ if (typeof value === "string") {
1232
+ result[key] = redactPii(value, options);
1233
+ } else if (Array.isArray(value)) {
1234
+ result[key] = value.map((item) => {
1235
+ if (typeof item === "string") return redactPii(item, options);
1236
+ if (item && typeof item === "object") return redactObjectPii(item, options);
1237
+ return item;
1238
+ });
1239
+ } else if (value && typeof value === "object") {
1240
+ result[key] = redactObjectPii(value, options);
1241
+ } else {
1242
+ result[key] = value;
1243
+ }
1244
+ }
1245
+ return result;
1246
+ }
1247
+
931
1248
  // src/validation/schema.ts
932
1249
  function validate(schema, source = "body") {
933
1250
  return (req, res, next) => {
@@ -1308,6 +1625,18 @@ function validateUrl(url, options = {}) {
1308
1625
  return { safe: false, reason: "loopback address" };
1309
1626
  }
1310
1627
  }
1628
+ if (!allowLocalhost || !allowPrivate) {
1629
+ const decimalCheck = checkDecimalIp(hostname, allowLocalhost, allowPrivate);
1630
+ if (decimalCheck) {
1631
+ return { safe: false, reason: decimalCheck };
1632
+ }
1633
+ }
1634
+ if (!allowLocalhost || !allowPrivate) {
1635
+ const octalCheck = checkOctalIp(hostname, allowLocalhost, allowPrivate);
1636
+ if (octalCheck) {
1637
+ return { safe: false, reason: octalCheck };
1638
+ }
1639
+ }
1311
1640
  if (!allowPrivate) {
1312
1641
  const privateCheck = checkPrivateIp(hostname);
1313
1642
  if (privateCheck) {
@@ -1339,13 +1668,93 @@ function checkPrivateIp(hostname) {
1339
1668
  if (/^0\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(hostname)) {
1340
1669
  return "current network address (0.0.0.0/8)";
1341
1670
  }
1342
- if (hostname === "metadata.google.internal" || hostname === "metadata.internal") {
1671
+ if (hostname === "metadata.google.internal" || hostname === "metadata.internal" || hostname === "metadata.azure.internal") {
1343
1672
  return "cloud metadata endpoint";
1344
1673
  }
1345
1674
  const ipv6 = hostname.replace(/^\[|\]$/g, "");
1346
1675
  if (ipv6 === "::1" || ipv6 === "::" || ipv6.startsWith("fc") || ipv6.startsWith("fd") || ipv6.startsWith("fe80")) {
1347
1676
  return "private IPv6 address";
1348
1677
  }
1678
+ const mappedDotted = ipv6.match(/^::ffff:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/i);
1679
+ if (mappedDotted) {
1680
+ const mappedIp = mappedDotted[1];
1681
+ if (/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(mappedIp)) {
1682
+ return "IPv6-mapped loopback address";
1683
+ }
1684
+ const mappedCheck = checkPrivateIp(mappedIp);
1685
+ if (mappedCheck) {
1686
+ return `IPv6-mapped ${mappedCheck}`;
1687
+ }
1688
+ }
1689
+ const mappedHex = ipv6.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i);
1690
+ if (mappedHex) {
1691
+ const hi = parseInt(mappedHex[1], 16);
1692
+ const lo = parseInt(mappedHex[2], 16);
1693
+ const a = hi >> 8 & 255;
1694
+ const b = hi & 255;
1695
+ const c = lo >> 8 & 255;
1696
+ const d = lo & 255;
1697
+ const dotted = `${a}.${b}.${c}.${d}`;
1698
+ if (a === 127) {
1699
+ return "IPv6-mapped loopback address";
1700
+ }
1701
+ const hexCheck = checkPrivateIp(dotted);
1702
+ if (hexCheck) {
1703
+ return `IPv6-mapped ${hexCheck}`;
1704
+ }
1705
+ }
1706
+ return null;
1707
+ }
1708
+ function checkDecimalIp(hostname, allowLocalhost, allowPrivate) {
1709
+ if (!/^\d+$/.test(hostname)) return null;
1710
+ const num = parseInt(hostname, 10);
1711
+ if (isNaN(num) || num < 0 || num > 4294967295) return null;
1712
+ const a = num >>> 24 & 255;
1713
+ const b = num >>> 16 & 255;
1714
+ const c = num >>> 8 & 255;
1715
+ const d = num & 255;
1716
+ const dotted = `${a}.${b}.${c}.${d}`;
1717
+ if (!allowLocalhost && a === 127) {
1718
+ return `loopback address (decimal IP: ${dotted})`;
1719
+ }
1720
+ if (!allowPrivate) {
1721
+ const privateCheck = checkPrivateIp(dotted);
1722
+ if (privateCheck) {
1723
+ return `${privateCheck} (decimal IP: ${dotted})`;
1724
+ }
1725
+ }
1726
+ return null;
1727
+ }
1728
+ function checkOctalIp(hostname, allowLocalhost, allowPrivate) {
1729
+ const parts = hostname.split(".");
1730
+ if (parts.length !== 4) return null;
1731
+ const hasAlternateNotation = parts.some((p) => /^0[0-7]+$/.test(p) || /^0x[0-9a-fA-F]+$/i.test(p));
1732
+ if (!hasAlternateNotation) return null;
1733
+ const octets = [];
1734
+ for (const part of parts) {
1735
+ let val;
1736
+ if (/^0x[0-9a-fA-F]+$/i.test(part)) {
1737
+ val = parseInt(part, 16);
1738
+ } else if (/^0[0-7]*$/.test(part)) {
1739
+ val = parseInt(part, 8);
1740
+ } else if (/^\d+$/.test(part)) {
1741
+ val = parseInt(part, 10);
1742
+ } else {
1743
+ return null;
1744
+ }
1745
+ if (val < 0 || val > 255) return null;
1746
+ octets.push(val);
1747
+ }
1748
+ const dotted = octets.join(".");
1749
+ if (!allowLocalhost && octets[0] === 127) {
1750
+ return `loopback address (octal IP: ${dotted})`;
1751
+ }
1752
+ if (!allowPrivate) {
1753
+ const privateCheck = checkPrivateIp(dotted);
1754
+ if (privateCheck) {
1755
+ return `${privateCheck} (octal IP: ${dotted})`;
1756
+ }
1757
+ }
1349
1758
  return null;
1350
1759
  }
1351
1760
 
@@ -1661,12 +2070,21 @@ function isValidEmailSyntax(email) {
1661
2070
  }
1662
2071
 
1663
2072
  // src/logging/redactor.ts
2073
+ var LOG_LEVELS = {
2074
+ debug: 0,
2075
+ info: 1,
2076
+ warn: 2,
2077
+ error: 3,
2078
+ silent: 4
2079
+ };
1664
2080
  function createSafeLogger(options = {}) {
1665
2081
  const {
1666
2082
  redactKeys = [],
1667
2083
  maxLength = REDACTION.DEFAULT_MAX_LENGTH,
1668
- redactPatterns = []
2084
+ redactPatterns = [],
2085
+ level: minLevel = "debug"
1669
2086
  } = options;
2087
+ const minLevelNum = LOG_LEVELS[minLevel] ?? 0;
1670
2088
  const allRedactKeys = /* @__PURE__ */ new Set([
1671
2089
  ...Array.from(REDACTION.SENSITIVE_KEYS),
1672
2090
  ...redactKeys.map((k) => k.toLowerCase())
@@ -1692,6 +2110,8 @@ function createSafeLogger(options = {}) {
1692
2110
  return result;
1693
2111
  }
1694
2112
  function log(level, message, data) {
2113
+ const levelNum = LOG_LEVELS[level] ?? 0;
2114
+ if (levelNum < minLevelNum) return;
1695
2115
  const entry = {
1696
2116
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1697
2117
  level,
@@ -2298,6 +2718,119 @@ function botProtection(options = {}) {
2298
2718
  next();
2299
2719
  };
2300
2720
  }
2721
+ var DEFAULTS = {
2722
+ cookieName: "_csrf",
2723
+ headerName: "x-csrf-token",
2724
+ fieldName: "_csrf",
2725
+ tokenLength: 32,
2726
+ protectedMethods: ["POST", "PUT", "PATCH", "DELETE"]
2727
+ };
2728
+ function generateCsrfToken(length = 32) {
2729
+ return randomBytes(length).toString("hex");
2730
+ }
2731
+ function validateCsrfToken(cookieToken, requestToken) {
2732
+ if (!cookieToken || !requestToken) return false;
2733
+ if (cookieToken.length !== requestToken.length) return false;
2734
+ let result = 0;
2735
+ for (let i = 0; i < cookieToken.length; i++) {
2736
+ result |= cookieToken.charCodeAt(i) ^ requestToken.charCodeAt(i);
2737
+ }
2738
+ return result === 0;
2739
+ }
2740
+ function getRequestToken(req, headerName, fieldName) {
2741
+ const headerToken = req.headers[headerName.toLowerCase()];
2742
+ if (typeof headerToken === "string" && headerToken) return headerToken;
2743
+ if (req.body && typeof req.body === "object" && fieldName in req.body) {
2744
+ const bodyToken = req.body[fieldName];
2745
+ if (typeof bodyToken === "string" && bodyToken) return bodyToken;
2746
+ }
2747
+ if (req.query && fieldName in req.query) {
2748
+ const queryToken = req.query[fieldName];
2749
+ if (typeof queryToken === "string" && queryToken) return queryToken;
2750
+ }
2751
+ return void 0;
2752
+ }
2753
+ function csrfProtection(options = {}) {
2754
+ const cookieName = options.cookieName ?? DEFAULTS.cookieName;
2755
+ const headerName = options.headerName ?? DEFAULTS.headerName;
2756
+ const fieldName = options.fieldName ?? DEFAULTS.fieldName;
2757
+ const tokenLength = options.tokenLength ?? DEFAULTS.tokenLength;
2758
+ const protectedMethods = options.protectedMethods ?? [...DEFAULTS.protectedMethods];
2759
+ const excludePaths = options.excludePaths ?? [];
2760
+ const isProduction = process.env.NODE_ENV === "production";
2761
+ const cookieOpts = {
2762
+ path: options.cookie?.path ?? "/",
2763
+ httpOnly: options.cookie?.httpOnly ?? false,
2764
+ // Must be readable by client JS
2765
+ secure: options.cookie?.secure ?? isProduction,
2766
+ sameSite: options.cookie?.sameSite ?? "Lax",
2767
+ domain: options.cookie?.domain
2768
+ };
2769
+ const defaultOnError = (_req, res, _next) => {
2770
+ res.status(403).json({
2771
+ error: "CSRF token validation failed",
2772
+ message: "Invalid or missing CSRF token. Include the token from the cookie in the X-CSRF-Token header."
2773
+ });
2774
+ };
2775
+ const onError = options.onError ?? defaultOnError;
2776
+ const protectedSet = new Set(protectedMethods.map((m) => m.toUpperCase()));
2777
+ return (req, res, next) => {
2778
+ const method = req.method.toUpperCase();
2779
+ const requestPath = req.path || req.url;
2780
+ if (excludePaths.some((p) => requestPath === p || requestPath.startsWith(p + "/"))) {
2781
+ return next();
2782
+ }
2783
+ req.csrfToken = () => {
2784
+ const existing = getCookieValue(req, cookieName);
2785
+ if (existing) return existing;
2786
+ const token = generateCsrfToken(tokenLength);
2787
+ setCsrfCookie(res, cookieName, token, cookieOpts);
2788
+ return token;
2789
+ };
2790
+ if (!protectedSet.has(method)) {
2791
+ const existing = getCookieValue(req, cookieName);
2792
+ if (!existing) {
2793
+ const token = generateCsrfToken(tokenLength);
2794
+ setCsrfCookie(res, cookieName, token, cookieOpts);
2795
+ }
2796
+ return next();
2797
+ }
2798
+ const cookieToken = getCookieValue(req, cookieName);
2799
+ if (!cookieToken) {
2800
+ return onError(req, res, next);
2801
+ }
2802
+ const requestToken = getRequestToken(req, headerName, fieldName);
2803
+ if (!requestToken) {
2804
+ return onError(req, res, next);
2805
+ }
2806
+ if (!validateCsrfToken(cookieToken, requestToken)) {
2807
+ return onError(req, res, next);
2808
+ }
2809
+ next();
2810
+ };
2811
+ }
2812
+ function getCookieValue(req, name) {
2813
+ if (req.cookies && typeof req.cookies === "object" && name in req.cookies) {
2814
+ return req.cookies[name];
2815
+ }
2816
+ const cookieHeader = req.headers.cookie;
2817
+ if (!cookieHeader) return void 0;
2818
+ const match = cookieHeader.match(new RegExp(`(?:^|;\\s*)${escapeRegex(name)}=([^;]*)`));
2819
+ return match ? decodeURIComponent(match[1]) : void 0;
2820
+ }
2821
+ function setCsrfCookie(res, name, token, opts) {
2822
+ const parts = [`${name}=${token}`];
2823
+ parts.push(`Path=${opts.path}`);
2824
+ if (opts.httpOnly) parts.push("HttpOnly");
2825
+ if (opts.secure) parts.push("Secure");
2826
+ parts.push(`SameSite=${opts.sameSite}`);
2827
+ if (opts.domain) parts.push(`Domain=${opts.domain}`);
2828
+ res.setHeader("Set-Cookie", parts.join("; "));
2829
+ }
2830
+ function escapeRegex(str) {
2831
+ return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2832
+ }
2833
+ var createCsrf = csrfProtection;
2301
2834
 
2302
2835
  // src/utils/ip.ts
2303
2836
  var PLATFORM_HEADERS = {
@@ -2562,6 +3095,6 @@ function createRedisStore(options) {
2562
3095
  return new RedisStore(options);
2563
3096
  }
2564
3097
 
2565
- export { ArcisError, ValidationError as ArcisValidationError, BLOCKED, ERRORS, HEADERS, INPUT, InputTooLargeError, MemoryStore, RATE_LIMIT, REDACTION, RateLimitError, RedisStore, SanitizationError, SecurityThreatError, VALIDATION, arcis, arcisWithMethods as arcisFunction, botProtection, createCors, createErrorHandler, createHeaders, createRateLimiter, createRedactor, createRedisStore, createSafeLogger, createSanitizer, createSecureCookies, createSlidingWindowLimiter, createTokenBucketLimiter, createValidator, main_default as default, detectBot, detectClientIp, detectCommandInjection, detectHeaderInjection, detectNoSqlInjection, detectPathTraversal, detectPrototypePollution, detectSql, detectXss, enforceSecureCookie, errorHandler, fingerprint, formatDuration, isDangerousExtension, isDangerousNoSqlKey, isDangerousProtoKey, isPrivateIp, isRedirectSafe, isUrlSafe, isValidEmailSyntax, parseDuration, rateLimit, safeCors, safeLog, sanitizeCommand, sanitizeFilename, sanitizeHeaderValue, sanitizeHeaders, sanitizeObject, sanitizePath, sanitizeSql, sanitizeString, sanitizeXss, secureCookieDefaults, securityHeaders, validate, validateEmail, validateFile, validateRedirect, validateUrl, verifyEmailMx };
3098
+ export { ArcisError, ValidationError as ArcisValidationError, BLOCKED, ERRORS, HEADERS, INPUT, InputTooLargeError, MemoryStore, RATE_LIMIT, REDACTION, RateLimitError, RedisStore, SanitizationError, SecurityThreatError, VALIDATION, arcis, arcisWithMethods as arcisFunction, botProtection, createCors, createCsrf, createErrorHandler, createHeaders, createRateLimiter, createRedactor, createRedisStore, createSafeLogger, createSanitizer, createSecureCookies, createSlidingWindowLimiter, createTokenBucketLimiter, createValidator, csrfProtection, main_default as default, detectBot, detectClientIp, detectCommandInjection, detectHeaderInjection, detectJsonpInjection, detectNoSqlInjection, detectPathTraversal, detectPii, detectPrototypePollution, detectSql, detectSsti, detectXss, detectXxe, enforceSecureCookie, errorHandler, fingerprint, formatDuration, generateCsrfToken, isDangerousExtension, isDangerousNoSqlKey, isDangerousProtoKey, isPrivateIp, isRedirectSafe, isUrlSafe, isValidEmailSyntax, parseDuration, rateLimit, redactObjectPii, redactPii, safeCors, safeLog, sanitizeCommand, sanitizeFilename, sanitizeHeaderValue, sanitizeHeaders, sanitizeJsonpCallback, sanitizeObject, sanitizePath, sanitizeSql, sanitizeSsti, sanitizeString, sanitizeXss, sanitizeXxe, scanObjectPii, scanPii, secureCookieDefaults, securityHeaders, validate, validateCsrfToken, validateEmail, validateFile, validateRedirect, validateUrl, verifyEmailMx };
2566
3099
  //# sourceMappingURL=index.mjs.map
2567
3100
  //# sourceMappingURL=index.mjs.map